C# Dynamically Creating Objects by Class Name

This is an example of how to use the System.Reflection namespace within .Net framework to look inside an assembly in an attempt to locate and instantiate a class of a specific type when you only know its string name and which fits a specific interface.

When would you use this?  Although not very common in everyday coding there really are a few times in my experience where this method has helped me out. For example I used an Enumeration with Attributes to hold various values. One of those Attributes contained the string name of the class which needed to be instantiated by the code using the Enumeration. Because at run-time I only had the string name of the class I was unable to actually instantiate the type or the class from just the string. The method below allowed me to pass in the string name of the class and get back an instantiation of that type in the form of its implemented Interface and then use that class as needed.

Lets see just how creative you can be, add a comment with an example of how you used it.

public static IPerson GetPersonObject(string className, out Type objectType)

        {

            //Get a reference to the assembly containing the target classes

            Assembly assembly = Assembly.Load("DynamicalClassInvokation");

 

            //Get a list of all the classes in that assembly

            List<Type> classes = assembly.GetTypes().ToList();

 

            //Locate the class by its string name

            objectType = classes.Single(x => x.Name.Equals(className, StringComparison.InvariantCultureIgnoreCase));

 

            //Create the object, cast it and return it to the caller

            return (IPerson)Activator.CreateInstance(objectType);

        }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s