Extract type at runtime

I have a Type name being passed as an input . "MyApp.Modules.Common.contact".

Using Activator.CreateInstance how do I construct this type in the method that I'm using. if I do it like this

Type typ = Type.GetType("MyApp.Modules.Common.contact")

the typ is always null. How do I fix this. Please help.

Jon Skeet
people
quotationmark

If you provide just the type name, Type.GetType will look in the currently-executing assembly, and mscorlib - but that's all. If you need to access a type in a different assembly, then either you need to get the assembly name in the type as well, e.g. "MyApp.Modules.Common.contact, MyApp.Modules.Common" (if the assembly name is "MyApp.Modules.Common" - or if you have an Assembly reference, you can use Assembly.GetType(string).

If you have no information about what assembly you should look in, but you're confident that the assembly has been loaded, you could potentially use AppDomain.GetAssemblies() to find the assemblies, and then look through each of those in turn, calling Assembly.GetType until you find a match.

I would encourage you to look at the design of where how the type information is being passed around though - ideally make sure that the assembly information is available.

people

See more on this question at Stackoverflow