I am trying to check if an "enum instance" contains more than one flag.
I do not care which Flags the "instance" contains, I just want to know if there are more than one
Additionally I really don't wanna use something like the following:
var state = Foo.Bar | Foo.Far;
Console.WriteLine(state.ToString().Count(x => x == ',') > 0); // True
There are more than a few different ways to accomplish what you want, I propose to do a bit (bitwise) check:
public static bool MoreThanOneFlag<TValue>(TValue flag) where TValue : Enum => (Convert.ToInt32(flag) & (Convert.ToInt32(flag) - 1)) != 0;
In the above code block, we check if flag
is not a power of two by checking using flag & (flag-1)) != 0
(the & operator) which computes the bitwise logical AND of its operands. If there's only one flag set, we assume then that the value would be a power of two, otherwise it's a non power of two.
Or, if you don't want a helper function just perform that check anywhere:
bool value = (multiState & (multiState -1)) != 0;
For more information about bitwise, please check out more here.
References :
Bitwise and shift operators (C# reference)