If you have something like this:
enum MyEnum
{
Value1,
Value2,
Value3,
Value4,
}
If you do MyEnum.Value2 | MyEnum.Value3
it will come up to be Value4
. That is because 1 | 2 = 3
. If you increase the first number to be 100000000 for example and end up with:
enum MyEnum
{
Value1=100000000,
Value2,
Value3,
Value4,
}
You will still have the same problem because 100000001 | 100000002 = 100000004
and that is Value4`.
Solution
The solution is to pick numbers that when you AND
or OR
them in whatever combination you will never get any of the others. Pick this numbers:
// 1000 0000 0000 0000 0000 0000 0000 0001 = 2,147,483,649
// 0100 0000 0000 0000 0000 0000 0000 0010 = 1,073,741,826
// 0010 0000 0000 0000 0000 0000 0000 0100 = 536,870,916
// 0001 0000 0000 0000 0000 0000 0000 1000 = 268,435,464
// 0000 1000 0000 0000 0000 0000 0001 0000 = 134,217,744
// 0000 0100 0000 0000 0000 0000 0010 0000 = 67,108,896
// 0000 0010 0000 0000 0000 0000 0100 0000 = 33,554,496
// 0000 0001 0000 0000 0000 0000 1000 0000 = 16,777,344
// 0000 0000 1000 0000 0000 0001 0000 0000 = 8,388,864
// 0000 0000 0100 0000 0000 0010 0000 0000 = 4,194,816
// 0000 0000 0010 0000 0000 0100 0000 0000 = 2,098,176
// 0000 0000 0001 0000 0000 1000 0000 0000 = 1,050,624
// 0000 0000 0000 1000 0001 0000 0000 0000 = 528,384
// 0000 0000 0000 0100 0010 0000 0000 0000 = 270,336
// 0000 0000 0000 0010 0100 0000 0000 0000 = 147,456
// 0000 0000 0000 0001 1000 0000 0000 0000 = 98,304
No matter how you OR
or AND
this numbers you will never get another one. As a result pick your enum to be:
enum MyEnum {
Value1 = 98304,
Value2 = 147456,
Value3 = 270336,
// etc
}
Lastly this will always be false if you OR the values in whatever combination: Enum.IsDefined(typeof(MyEnum), MyEnum.Value1 | MyEnum.Value2)
So you can create this helper function
bool IsEnumValid(MyEnum enumValue)
{
return Enum.IsDefined(typeof(MyEnum), enumValue);
}
enum
s at all. They are essentially named and categorised integers, not much more. – Faovar onlyOneOption = (OnlyOneOption)-9999;
because that's also a valid integer value. What you should rely on is the specific members and not the values. Just like CompuChip suggests in his answer – Kulak