Convert String to Type in C# [duplicate]
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?
Solution 1:
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);
Solution 2:
Try:
Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;
Jon Skeet is right as usually :)
Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:
YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");