Instantiate a class from its name in string

3

I have a select where I have some options

  • Test1
  • Test2
  • Test3

I have a model for each option

public class Teste1() {
//atributos e métodos
} 

I would like, in a certain part of my system, to receive this string ex: "Test1"

and create an object of type Test1

something like:

var objeto = new "Teste1"

In other words, generating an object from its name

    
asked by anonymous 30.10.2017 / 13:24

1 answer

2

This can be done using Activator.CreateInstance .

There is usually no real need to work on this, so it's good to analyze the problem well and rethink the use of this mechanism.

The code would look like this:

var objeto = Activator.CreateInstance("Assembly", "Teste1");

Where Assembly is the name of the assembly where the class is. You can use null if the assembly is what is running.

    
30.10.2017 / 13:32