6

Using reflection, I need to investigate a user DLL and create an object of a class in it.

What is the simple way of doing it?

gil
  • 2,248
  • 6
  • 25
  • 31

5 Answers5

14

Try Activator.CreateInstance.

jfs
  • 16,758
  • 13
  • 62
  • 88
3

System.Reflection.Assembly is the class you will want to use. It contains many method for iterating over the types contained with a user DLL. You can iterate through each class, perhaps see if it inherits from a particular interface etc.

http://msdn.microsoft.com/en-us/library/system.reflection.assembly_members.aspx

Investigate Assembly.GetTypes() method for getting the list of types, or Assembly.GetExportedTypes() for the public ones only.

samjudson
  • 56,243
  • 7
  • 59
  • 69
1

You can create an instance of a class from a Type object using Activator.CreateInstance, to get all types in a dll you can use Assembly.GetTypes

Nir
  • 29,306
  • 10
  • 67
  • 103
1

Take a look at these links:

http://www.java2s.com/Code/CSharp/Development-Class/Createanobjectusingreflection.htm

http://msdn.microsoft.com/en-us/library/k3a58006.aspx

You basically use reflection to load an assembly, then find a type you're interested in. Once you have the type, you can ask to find it's constructors or other methods / properties. Once you have the constructor, you can invoke it. Easy!

Mark Ingram
  • 71,849
  • 51
  • 176
  • 230
1

As it has already been said, you need to poke the System.Reflection namespace.

If you know in advance the location/name of the DLL you want to load, you need to iterate through the Assembly.GetTypes().

In Pseudocode it would look something like this:

Create and assembly object.

Iterate through all the types contained in the assembly.

Once you find the one you are looking for, invoke it (CreateInstance)…

Use it wisely.

;)

I have plenty of Reflection code if you want to take a look around, but the task is really simple and there are at least a dozen of articles with samples out there in the wild. (Aka Google). Despite that, the MSDN is your friend for Reflection Reference.

Martin Marconcini
  • 26,875
  • 19
  • 106
  • 144