Advertisement
Advertisement


Creating an object without knowing the class name at design time


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?

2015/06/17
1
5
6/17/2015 9:49:05 AM

Accepted Answer

2008/09/10
13
9/10/2008 8:56:22 AM


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

2008/09/10

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!

2008/09/10

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.

2008/09/10

Source: https://stackoverflow.com/questions/53649
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]