user990635
user990635

Reputation: 4249

How to get a type from a string?

Why does var type = Type.GetType("System.Windows.Forms.TextBox"); return null?

I am trying to get the type of a TextBox type from a string.

Upvotes: 1

Views: 126

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156978

You should include the full assembly name too:

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

Note the documentation on MSDN (emphasis mine):

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.

So only mscorlib and the Assembly.GetExecutingAssembly() can be resolved using the type name only, else you need the full assembly name too.

Upvotes: 7

Enigmativity
Enigmativity

Reputation: 117064

You should also include the assembly name and public tokens, etc:

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

Upvotes: 4

Related Questions