views:

455

answers:

3

I want to get a System.Type given only the type name in a string.

For instance, if I have an object:
MyClass abc = new MyClass();

I can then say:
System.Type type = abc.GetType();

But what if all I have is:
string className = "MyClass";

+12  A: 
Type type = Type.GetType("foo.bar.MyClass, foo.bar");

MSDN. Make sure the name is Assembly Qualified.

Chris Marasti-Georg
An important note: It requires the fully qualified type name.
leppie
+3  A: 
Type type = Type.GetType("MyClass");

Make sure to include the namespace. There are overloads of the method that control case-sensitivity and whether an exception is thrown if the type name isn't found.

jalbert
Incorrect, you must also specify the assembly.
Chris Marasti-Georg
That wont work :)
leppie
From the docs, "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."
jalbert
Is the type in the currently executing assembly? The OP didn't specify.
Chris Marasti-Georg
+2  A: 

To create an instance of your class after you get the type, and invoke a method -

Type type = Type.GetType("foo.bar.MyClass, foo.bar");
object instanceObject = System.Reflection.Activator.CreateInstance(type);
type.InvokeMember(method, BindingFlags.InvokeMethod, null, instanceObject, new object[0]);
Terrapin