0
votes

here is my code:

using System.Reflection;
Public class ClassA
{
    public ClassA()
    {
        ClassB classB = new ClassB();
        classB.UsingType = "ClassD";
        ClassB.Do();
    }
}
Public class ClassB
{
    public string UsingType { get; set; }
    public void Do()
    {
        ClassC classC = new ClassC();
        Type type = Type.GetType(UsingType);
        Object obj = Activator.CreateInstance(type);
        classC.Do(obj); // Error : cannot convert from 'object' to 'ClassD'
    }
}
public class ClassC
{
    public void Do(ClassD classD) // If I change "ClassD" to "Object" It works!!
    {
        //Do something with classD
    }
}

I get this error: "cannot convert from 'object' to 'ClassD'."

If I change "Do" method argument of "ClassC" from "ClassD" to "Object" the error goes away and then I can cast it to "ClassD" and use that parameter. But that's not what I want.

Is there a way to cast "obj" by "UsingType" string to "ClassD" (in "Do" method of "ClassB") and get rid of the compile time error?

In other words: (since "ClassA" knows the type name string and passes it to "ClassB") how can I cast from "Object" to the type that "ClassC" asks for?

1
The compiler cn´t know of which runtime-type obj actually is. This information exists only when actually executing your program. Thus even if you could infer a cast by using a runtime-type at least during compile-time all you get was an object instead of ClassA. This is the price of sing reflection: you lose any information on the actual time at compile-time and thus can deal only with object.HimBromBeere
My gut tells me your design is flawed. Can you explain what problem you're trying to solve or what your requirements are?Craig W.
What I want to do is to instantiate and pass an object to another method by knowing it's type name at run time.amir mola

1 Answers

0
votes

Since you're sure that objwill be of type ClassC, just cast it to the expected type.

ClassC obj = (ClassC)Activator.CreateInstance(type);
classC.Do(obj); 

To further explain what this does: Object is a generic type, and has only the properties/methods that are globally available (such as ToString(), or GetHashCode().)

Casting it to a class means that the compiler will try to convert it, and return null if said conversion fails.