Instantiating generic type of an Enum

Asked

Viewed 129 times

2

I would like to instantiate a class from an Enum, for example:

Instead of doing:

var classeGenerica;

if (viewModel.tipoCarro == 1)
   classeGenerica = new classeCarro();
else
   classeGenerica = new classeOutros();

Something that went something like this:

TipoCarroEnum genericoEnum = (TipoCarroEnum)tipoCarro;
var generico = new genericoEnum();
  • I don’t understand. You want to use a Enum to instill a class? You cannot instantiate a Enum.

  • wanted to convert it into type or object for instantiation

  • For what? What do you want to take from a so-called instance of Enum? An enumerator is nothing more than an abstract class where each value inside represents a int.

  • to avoid making an if for each type

  • Makes a switch if you want to assign each value of the enum for a specific class. Or if you want, you can use the Enum.Parse() but he doesn’t fit his situation. It really doesn’t make sense to want to instantiate a enum, besides being impossible, you will actually be instantiating an entire number, not a class.

  • 3

    I understood what you want to do. In other languages it would be an easier job. Take a look at Factory Pattern implementations for C#, maybe give you some ideas.

Show 1 more comment

1 answer

2

You can exchange the "ifs" for switch case.

Example:

//Enum com os tipos de carros
public enum CarroEnum
{
    BMW = 1,
    Ford = 2,
    Audi = 3,
    Toyota = 4
}

//--------------Implementação do enum

//O Enum utilizado neste exemplo será o CarroEnum.Audi
var tipoCaroo = CarroEnum.Audi;

switch (tipoCaroo)
{
    case CarroEnum.Audi:
        //Instancia classe referente ao carro Audi
        break;

    case CarroEnum.BMW:
        //Instancia classe referente ao carro BMW
        break;

    case CarroEnum.Ford:
        //Instancia classe referente ao carro Ford
        break;

    case CarroEnum.Toyota:
        //Instancia classe referente ao carro Toyota
        break;

    default:
        //Caso não entre nos cases acima, cairá aqui.
        break;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.