Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object without knowing the class name at design time

Tags:

c#

reflection

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?

like image 225
gil Avatar asked Sep 10 '08 08:09

gil


3 Answers

Try Activator.CreateInstance.

like image 124
jfs Avatar answered Sep 24 '22 06:09

jfs


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.

like image 36
samjudson Avatar answered Sep 24 '22 06:09

samjudson


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

like image 41
Nir Avatar answered Sep 23 '22 06:09

Nir