0

After loading an assembly, when instantiating it:

Assembly asm = Assembly.LoadFile(@"c:\file.dll");
Type type = asm.GetType("DLLTYPE");
object instance = Activator.CreateInstance(type);

How C# know the type?
From my logic, the dll should have header which define the object type.
so why is the DLLTYPE string for ?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
ilansch
  • 4,784
  • 7
  • 47
  • 96
  • Possible duplicate: http://stackoverflow.com/questions/465488/can-i-load-a-net-assembly-at-runtime-and-instantiate-a-type-knowing-only-the-na?rq=1 – Rotem Jan 17 '13 at 14:14
  • 1
    You should perhaps look int "MEF" (Managed Extensability Framework) – TGlatzer Jan 17 '13 at 14:14

1 Answers1

3

How C# know the type?

You've passed it as parameter:

Type type = asm.GetType("DLLTYPE");

so why is the "DLLTYPE" string for ?

It's the namespace and the class name that you want to instantiate:

Namespace.ClassName

Be careful because this method will return null if you make a mistake in the typename. If you want to ensure that the type exists you could use the following overload:

Type type = asm.GetType("Namespace.ClassName", true);

This will throw an exception instead of returning null which will be easier to debug instead of the NRE you would otherwise get on the Activator.CreateInstance method.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • In my program the user browse and load DLL with OpenFileDialog, so how can i know the type ? i thought the type is 'declared' inside the DLL. at least a main class to use. – ilansch Jan 17 '13 at 14:32
  • An assembly can contain multiple types. If the user selects only an assembly which type do you want to load? – Darin Dimitrov Jan 17 '13 at 15:39
  • how do i know what he choose ? how can i recognize his choice ? what is the proper way ? – ilansch Jan 20 '13 at 06:57
  • That will depend on your application and how are you listing the possible choices to the user. Or maybe you have an input field where he could type it in. In all cases you will get the type as a string from the user and then you could use the `GetType` method to fetch the actual type at runtime. – Darin Dimitrov Jan 20 '13 at 17:34