I have two enums and a generic method. The generic type T could be either one of the enums.
public enum myEnumA
{
a,
b
}
public enum myEnumB
{
c,
d
}
public void myMethod<T>()
{
if (typeof(T) is myEnumA)
{
//do something
}
else if (typeof (T) is myEnumB)
{
//do something else
}
}
The compiler tells me "the given expression is never of the provided type" regarding the if check. Is there a way to tell which exact enum it is at run time?
You want:
if (typeof(T) == typeof(MyEnumA))
to compare the types. The is
operator is for testing whether a value is of a particular type.
Note that having to test for particular types within a generic method suggests that it might not really be very generic after all - consider using overloads or just entirely separate methods instead.
See more on this question at Stackoverflow