My application defines several enum
s that include the [Flags]
attribute.
I wanted to write a small utility method to check if a flag was set for any of those enum
s and I came up with the following.
protected static bool IsFlagSet<T>(ref T value, ref T flags)
{
return ((value & flags) == flags);
}
But this gives me the error "Operator '&' cannot be applied to operands of type 'T' and 'T'".
Can this be made to work?
The Enum class already has a utility function: Enum.HasFlag(Flag f)
, see the example on MSDN
if (petsInFamily.HasFlag(Pet.Dog))
familiesWithDog++;
Note: This was introduced in C# 4. And while it's very readable it may have some performance issues.
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