Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection of C# Types: GetType( "myType" ) vs typeof( myType ) behavior differs. Why?

I would like to use reflection to get an assembly for a supplied namespace and type. I would prefer to supply these as strings. It is probably important to note that the namespace and type are defined in an assembly other than the one that is executing this code, but the executing code assembly does have a reference to that other assembly.

My question is why does the static GetType(string) method return null, while if I hard-code the namespace and class and use typeof() as in the if statement, I get the required result?

Here is the code:

   string fullClassName = "MyNameSpace.MyClass";
   Type t = Type.GetType( fullClassName  ); // this returns null!
   if ( t == null ) 
   {
      t = typeof(MyNameSpace.MyClass); // this returns a valid type!
   }

Thanks for any insights you may have...

like image 688
Steve L Avatar asked May 30 '13 14:05

Steve L


2 Answers

GetType actually queries a specific assembly (at runtime) for a type that might be defined within the assembly (Similar to new Object().GetType()). typeof on the other hand is determined at compile time.

For example:

// Nonsense. "Control" is not in the same assembly as "String"
Console.WriteLine(typeof(String).Assembly.GetType("System.Windows.Controls.Control"));

// This works though because "Control" is in the same assembly as "Window"
Console.WriteLine(typeof(Window).Assembly.GetType("System.Windows.Controls.Control"));
like image 175
sircodesalot Avatar answered Sep 27 '22 00:09

sircodesalot


Read this C#.NET - Type.GetType("System.Windows.Forms.Form") returns null

Type t = Type.GetType("MyObject"); //null

requires that you pass in a fully qualified assembly type string (see answers from link above)

Type t = typeof(MyObject); //Type representing MyObject

The compiler/runtime knows the type already becuase you've passed it in directly.

Consideration:

MyObject might exist as different things in different assemblies, therefore, why should Type.GetType() know which one your're talking about? - that is why you must pass in a fully qualified string - so then it knows exactly where to look and what to look for.

like image 42
Matthew Layton Avatar answered Sep 27 '22 00:09

Matthew Layton