Convert String to Type in C#
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);
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");
If you really want to get the type by name you may use the following:
System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");
Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.