Friday, 13 February 2015

Creating Object of a Class dynamically when you have name of the Class as string in C#?

How to create an object of a class dynamically when you have the name of class as string in c#. Here is the solution.

First, get the type of the class.
Below helper method Returns the Type of your class. Here Solutions.Common is the Namespace of your class. To get the Version and PublicKeyToken, go to run (window+r) , type assembly, search for your assembly, right click , properties and get these details.

 public static Type GetTypeFromClassName(string ClassName)
        {
            string ss = string.Format("Solutions.Common.{0}, Solutions.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3a6a3aa5a3aed1e3", ClassName);
            Type typeYouWant = Type.GetType(ss);
            if (typeYouWant != null)
            {
                return typeYouWant;
            }
            return null;
        }
So object of any class can be created by using above helper method as below:

Type CustomClassType = Helpers.GetTypeFromStringFromCommon("CustomClassName");
var CustomObj = Activator.CreateInstance(CustomClassType ); 
Now you have the object of your class using the string ClassName.

Hope it helped you.