Question

I have a solution that contains two projects. First of let me describe my scenario. Project 1: holds a base class calls MyBaseClass with the following two property and method that i'm interested in:

TypeToLoad - static string property of which inherited class to instantiate with simple get/set functionality.

Instance - static property which returns a MyBaseClass instance of the type specified in TypeToLoad with the following lines of code:

public static MyBaseClass Instance{
   return (MyBaseClass)Activator.CreateInstance(Type.typeof(TypeToLoad));
}

now in the second project I inherit MyBaseClass as follow(of course proper namespace and references have been added).

public class MyInheritClass : MyBaseClass {
    //implements all other functions of MyBaseClass;
}

and one of my other code file, in the same project as MyInheritClass, I have the following lines of code:

Type myType = Type.typeof("MyInheritClass"); //returns the correct "Type"
MyBaseClass.TypeToLoad = "MyInheritClass";
MyBaseClass myInstance = MyBaseClass.Instance; //Errors... because Type.typeof(...) could not resolve "MyInheritClass".

When I move MyInheritClass code file into the same project as MyBaseClass the code runs just fine.

My question is, is there anyway to create and instance of MyInheritClass using MyBaseClass.Instance by setting MyBaseClass.TypeToLoad = "MyInheritClass" without having to have these two classes in the same project (MyBaseClass in the base DLL class library and MyInheritClass in another project referencing MyBaseclass DLL library) ?

I've tried to search for reflections, Activator but wasn't able to find what I was looking for. Maybe I don't know the correct terminology for this.

Was it helpful?

Solution

Assuming you actually mean Type.GetType() (and not Type.typeof(), which won't compile), then it's clearly documented as doing exactly what you're observing:

The assembly-qualified name of the type to get. […] If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

It also explains how to fix it: ad the name of the assembly to the type name. So, if your type is called in MyInheritClass, it's in the MyNamespace namespace and in MyAssembly assembly (usually the same as the project name), you could set the type name to

MyNamespace.MyInheritClass, MyAssembly

and it should work.

Also, you should avoid using strings for type names, using the actual Type objects is much safer. TypeToLoad should be of type Type, not string.

Or, maybe, you shouldn't use a design like this at all. I don't know why are you doing this, but I'm pretty sure there is a better solution that doesn't involve setting static fields on a base class like this. (What happens when you have two types that implement the same base class?)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top