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.

Comments

Popular posts from this blog

SharePoint Online (O365) OAuth Authentication | Authorizing REST API calls against SharePoint Online Site | Get Access token from SharePoint Online | Set up OAuth for SharePoint Online Office 365

SharePoint 2013 REST API Reference

Simple Risk Assessment Matrix table with resultant risk calculation

Kendo UI (Core JavaScript) grid Server Paging, Server Sorting and Server Filtering with Dynamic SQL queries

Sharepoint- Using an Image From formatmap32x32.png in a Ribbon Control