Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

287
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda