Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic enum cast to specific enum

Tags:

c#

enums

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);
    }    
}
like image 527
renathy Avatar asked Jul 16 '15 06:07

renathy


2 Answers

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.

like image 171
Luaan Avatar answered Oct 06 '22 02:10

Luaan


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.

like image 34
Mike Zboray Avatar answered Oct 06 '22 02:10

Mike Zboray