Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

458
Views
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 answers
Answer question

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 Report

0

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

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!