How do you instantiate a class given its name in C#

Manoj Gokhale 0 Reputation points
2024-10-05T15:39:24.8833333+00:00

I have over 1000 classes. The user inputs the name of the class and it is expected to create an object of that class. I do not wish to have an if .. else set of 1000 class names, but want to get an object of the class whose name is inputted.

I do not want

if (input text = "class1")

{

 return ( new class1());

}

else if (input text = "class2")

{

 return ( new class2());

}

.........................

Please help me

regards

Manoj Gokhale

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 122.5K Reputation points
    2024-10-05T17:32:30.08+00:00

    The name must include the corresponding namespace. It can be prepended to the class name. For example:

    string input = "Class3";
    string name = "MyNamespace." + input;
    
    object obj = Activator.CreateInstance( assemblyName: null, typeName: name ).Unwrap();
    

    or

    string input = "Class3";
    string name = "MyNamespace." + input;
    
    Type type = Type.GetType( name );
    object obj = Activator.CreateInstance( type );
    

    See also other forms of Activator.CreateInstance and Type.GetType.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.