0

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.

Amit
  • 45,440
  • 9
  • 78
  • 110
Jayaraman
  • 147
  • 1
  • 11
  • where declare this type? possibly before you need load assembly with this type. Also check type name for a typo or something like – Grundy Jul 01 '15 at 07:01
  • "If the assembly has not been saved to disk when GetType is called, the method returns null.", lots of other reasons in the remarks of the [documentation](https://msdn.microsoft.com/en-us/library/w3f99sx1%28v=vs.110%29.aspx) too, do any of these reasons apply? – Sayse Jul 01 '15 at 07:03
  • Is it in same assembly? If not try: `Type typ = Type.GetType("MyApp.Modules.Common.contact, "+assemblyName)` – Matt Jul 01 '15 at 07:09

1 Answers1

5

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194