Borrowing the code from this question How do I check if more than one enum flag is set? I have tried to implement a generic extension that performs this test.
My first attempt was the following.
public static bool ExactlyOneFlagSet(this Enum enumValue)
{
return !((enumValue & (enumValue - 1)) != 0);
}
Which resulted in
Operator '-' cannot be applied to operands of type 'System.Enum' and 'int'
OK make sense, so I thought I'd try something like this
public static bool ExactlyOneFlagSet<T>(this T enumValue) where T : struct, IConvertible
{
return !(((int)enumValue & ((int)enumValue - 1)) != 0);
}
Which resulted in
Cannot convert type 'T' to 'int'
Which also makes sense after reading about this behaviour but then how on earth can this extension method be implemented. Anyone kind enough to help???