Question

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?

Was it helpful?

Solution

OTHER TIPS

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.

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

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!

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top