0

I am asking the question in the title because this works:

FooBar fooBar = new FooBar();

It hits the constructor in FooBar, etc. But this returns null:

Type type = Type.GetType("FooBar");

Both FooBar and the class from which I am trying to do this are in the same namespace, the same project, etc.

I've looked over this thread:

Type.GetType("namespace.a.b.ClassName") returns null

According to that accepted answer (and some others), this "only works when the type is found in either mscorlib.dll or the currently executing assembly."

If the two classes are in the same namespace and the same project (ie: same .dll) would that not make the same executing assembly?

What am I doing wrong?

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • I suspect that the reason why you are getting a "NULL" is not because they are in different executing assemblies (which they don't appear to be) but rather in the order that the CLR compiles your code ("just in time"). Since GetType("FooBar") does not instantiate the class if it has not been compiled then runtime does not know it exists – DaniDev Nov 16 '17 at 23:31
  • Why use `Type.GetType` at all? Why not use `typeof(FooBar)`? – mason Nov 17 '17 at 00:00
  • @mason - doing this in a factory pattern where the name of the class to instantiate is passed in as a string – Casey Crookston Nov 17 '17 at 14:40
  • Why? Seems like that shouldn't be necessary either. Why not use generics? – mason Nov 17 '17 at 14:42
  • The app is a very small, lightweight windows service app. It has a dozen or so possible classes that implement a given interface. We won't know until runtime which class to instantiate, and the way we know the class to instantiate is by extracting it's name from a json string which gets deserialized. I'm open to better ideas, but, the name of the class comes to this app in the form of a string. – Casey Crookston Nov 17 '17 at 14:59

2 Answers2

2

Even though it's in the same assembly and namespace, you still need to provide the namespace. It's just the assembly qualified name you can skip.

Type type = Type.GetType("YourNamespace.FooBar");
Allrameest
  • 4,364
  • 2
  • 34
  • 50
1

From the documentation:

typeName. The assembly-qualified name of the type to get. See AssemblyQualifiedName. 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.

So you still need to provide the namespace, e.g.

var type = Type.GetType("MyNamespace.FooBar");

If you really don't want to provide the namespace for some reason, as an alternative, you could just as easily do something like this:

var type = System.Reflection.Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(a => a.Name == "FooBar");
John Wu
  • 50,556
  • 8
  • 44
  • 80