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

460
Vistas
C# generic enum cast to specific enum

I have generic method that accepts "T" type and this is enumerator. Inside the method I have to call helper class methods and method name depands on type of enumerator.

public Meth<T> (T type) {

    if (typeof(T) == typeof(FirstEnumType)) {
       FirstEnumType t = ??? // I somehow need to convert T type to FirstEnumType
       this.helperFirstCalcBll(t);
    }
    else 
    {
        SecondEnumType t = ??? // I somehow need to convert T type to SecondEnumType
       this.helperSecondCalcBll(t);
    }    
}
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

There is no valid cast from an arbitrary type to an enum type so this is not allowed. You need to cast to object first:

FirstEnumType t = (FirstEnumType)(object)type;

This "tricks" the compiler by upcasting to object (which is always valid) then down-casts to the enum type. Assuming you have done a runtime type check, the downcast will never fail. However implementing this in the else branch, as given, isn't guaranteed to work.

One would question why the method is even generic in the first place but that is how you can make this particular method work.

over 4 years ago · Santiago Trujillo Denunciar

0

public void Meth(FirstEnumType type) {
    this.helperFirstCalcBll(type);
}
public void Meth(SecondEnumType type) {
    this.helperSecondCalcBll(type);
}
over 4 years ago · Santiago Trujillo Denunciar

0

This is something dynamic is very useful for:

public void Meth<T>(T enumValue) where T : struct
{
  InternalMeth((dynamic)enumValue);
}

private void InternalMeth(FirstEnumType enumValue)
{
  this.helperFirstCalcBll(enumValue);
}

private void InternalMeth(SecondEnumType enumValue)
{
  this.helperSecondCalcBll(enumValue);
}

private void InternalMeth(object enumValue)
{
  // Do whatever fallback you need
}

This avoids having to write all those if (typeof(T) == typeof(...)) and everything - you let the dynamic dispatch handle picking the best overload at runtime. The object overload is there if all the others fail, so that you can e.g. throw an exception.

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