GetType returning null

  • Thread starter Thread starter Marco
  • Start date Start date
M

Marco

Hi.

I am trying to get a type object using GetType. For this,
I use:

Type type = Type.GetType("System.Windows.Forms.TextBox");

But after this line, when I check, type is null.
What am I doing wrong ? How to do it right ?

Thank you and God bless.

_____
Marco
 
Marco said:
I am trying to get a type object using GetType. For this,
I use:

Type type = Type.GetType("System.Windows.Forms.TextBox");

But after this line, when I check, type is null.
What am I doing wrong ? How to do it right ?

Type.GetType only looks in the currently executing assembly and
mscorlib.

For the above, you should use

Type type = typeof(System.Windows.Forms.TextBox);

If you need to dynamically get another type, you should work out what
assembly it should be part of, and call Assembly.GetType appropriately.
 
Jon and Marco,

Jon's statement:

Type.GetType only looks in the currently executing assembly and mscorlib.

Isn't completely true. If the type name that is passed in unqualified
(which is indeed the form that the original caller was using), it will
search only the current assembly and mscorlib (there is an inconsistency in
the documentation that states that it will look in System.dll and in the
current assembly). However, the following will work:

Type.GetType("System.Windows.Forms.TextBox, System.Windows.Forms,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

So, as a general rule, when doing dynamic discovery of types, make sure
to store the fully qualified name of the type (which means full namespace,
full assembly name with version, public key, etc, etc if they exist).

However, if you know that the type that you have to get is a TextBox,
then Jon's suggestion of using typeof is the more reliable solution.

Hope this helps.
 
Type type = Type.GetType("System.Windows.Forms.TextBox");

try use typeof(TextBox) instead. this should be more reliable.
 
Nicholas Paldino said:
Type.GetType only looks in the currently executing assembly and mscorlib.

Isn't completely true. If the type name that is passed in unqualified
(which is indeed the form that the original caller was using), it will
search only the current assembly and mscorlib (there is an inconsistency in
the documentation that states that it will look in System.dll and in the
current assembly). However, the following will work:

<snip>

Apologies - yes indeed. Sorry for not being clear :(
Type.GetType("System.Windows.Forms.TextBox, System.Windows.Forms,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

So, as a general rule, when doing dynamic discovery of types, make sure
to store the fully qualified name of the type (which means full namespace,
full assembly name with version, public key, etc, etc if they exist).

Or load the assembly separately and use Assembly.GetType.
 
Back
Top