Elliko
Elliko

Reputation: 81

Is there a way to tell which exact enum I'm working with at run-time?

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?

Upvotes: 1

Views: 83

Answers (3)

dbc
dbc

Reputation: 116786

You can do

if (typeof(T) == typeof(myEnumA))

Your types are enums, which are sealed. Were your types not sealed, you might need to use the IsAssignableFrom method, to check for subclassing, e.g.:

if (typeof(BaseTypeA).IsAssignableFrom(typeof(T))

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

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.

Upvotes: 4

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Because typeof returns a Type instance and that will never be compatible with your enum types. So is will return always false. Instead you need

if (typeof(T) == typeof(myEnumA))

Upvotes: 1

Related Questions