Convert String to Type in C#

vinhent picture vinhent · Jun 19, 2012 · Viewed 232.6k times · Source

If I receive a string that contains the name of a class and I want to convert this string to a real type (the one in the string), how can I do this?

I tried

Type.GetType("System.Int32")

for example, it appears to work.

But when I try with my own object, it always returns null ...

I have no idea what will be in the string in advance so it's my only source for converting it to its real type.

Type.GetType("NameSpace.MyClasse");

Any idea?

Answer

Jon Skeet picture Jon Skeet · Jun 19, 2012

You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well:

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information.

Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType:

Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);