Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

288
Visualizações
How to cast a variable of an enum generic type to int and back

I am using C# to write a class that takes an enum type parameter, like this:

class EnumWrapper<T>
    where T: Enum
{
}

Inside the class, I have a method that takes an argument of type T, and I need to cast it to an int, like this:

void DoSomething(T arg)
{
    int a = (int)arg;
}

But the compiler issues a CS0030 error "Cannot convert type 'T' to 'int'. Something similar happens when I try to cast an int back into a T. However, this works with a fixed enum type that is not provided via a type parameter. For example, this works fine:

void DoSomething(DayOfWeek arg)
{
    int a = (int)arg;
}

Why is this happening, and how can I cast between a generic enum type and int?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You may add IConvertible to generic constraint and use ToInt32 method, something like

class EnumWrapper<T>
    where T : Enum, IConvertible
{
    void DoSomething(T arg)
    {
        int a = arg.ToInt32(null);
    }
}

Have a look at the Enum constraint for details. Also, as mentioned in comments, it isn't necessary that your enum is based on int type

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda