Convert string to class at run time in C#

Viewed 221

I have Class Name in Database like "Workcenter" and "Holidays" etc. and my project namespace is "CMMI.API.Model" after concate the namespace and table name it become "CMMI.API.Model.Holidays" and "CMMI.API.Model.Workcenter" and I want to convert this string class name to application class name. Is Their any way to convert it. There can be numbers of classes even I don't know the name of classes.

And I don't want to use like this below:

object obj;
switch(className)
{
         case "Foo":
        obj = new Foo();
        break;
        case "bar":
        obj = new Bar();
        break;
    ...
}

Instead of creating new instance of class in switch statement i want simply convert string to class.

Any help will be very much appreciated

1 Answers

Try this

const string objectToInstantiate = "SampleProject.Domain.MyNewTestClass, MyTestProject";
 
var objectType = Type.GetType(objectToInstantiate);

var instantiatedObject = Activator.CreateInstance(objectType) as ITestClass;

Still it would be hard to do this if you have different constructors, but with default constructors it will work fine

You also could find another overloads there : https://docs.microsoft.com/en-US/dotnet/api/system.activator.createinstance?view=netcore-3.1

Related