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);
}
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With