Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HasFlag with a generic enum?

I am just starting with Generics in C# but have run into a problem early on, how can I call .HasFlag() on a generic Enum?

public class Example<TEnum> where TEnum : struct {
}

How can I add the [Flags] attribute to it?

like image 968
DevDave Avatar asked Mar 01 '12 16:03

DevDave


1 Answers

Calling the instance method will require boxing anyway, so, since you can't constrain to Enum, just abandon generics and use Enum. For example, instead of:

void Something(TEnum enumValue, TEnum flags)
{
    if (enumValue.HasFlags(flags))
        //do something ...
}

Do this:

void Something(Enum enumValue, Enum flags)
{
    if (enumValue.HasFlags(flags))
        //do something ...
}

In a generic method, you could achieve your goal like this:

void Something(TEnum enumValue, TEnum flags)
{
    Enum castValue = (Enum)(object)enumValue;
    Enum castFlags = (Enum)(object)flags;

    if (castValue.HasFlags(castFlags))
        //do something ...
}

This will throw an exception at runtime if you call the method with a value type that isn't an enum. You could also cast via ValueType rather than object, since the type parameter is known to represent a value type:

Enum castValue = (Enum)(ValueType)enumValue;
like image 66
phoog Avatar answered Oct 13 '22 23:10

phoog