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

459
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

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

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 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