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=, 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.

Vikas Kottari

Hi. I’m a SharePoint Developer. I’m Microsoft Certified Professional on SharePoint. I work on O365, SharePoint 2016/2013/2010, SPFx and also I’m Full stack .NET Developer. I’m Foodie, Dreamer and Photographer. Inspired to make things looks better.