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.
Hope it helped you.
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)So object of any class can be created by using above helper method as below:
{
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;
}
Type CustomClassType = Helpers.GetTypeFromStringFromCommon("CustomClassName");Now you have the object of your class using the string ClassName.
var CustomObj = Activator.CreateInstance(CustomClassType );
Hope it helped you.
Comments
Post a Comment