I have following enum with flags attribute:
[Flags]
public enum MyEnum
{
None = 0,
First = 1,
Second= 2,
Third= 4,
.
.
.
Unknown = All >> 1,
All = ~None,
}
and I want the Unknown
value to be the last before the All
value. So I thought that the right-shift operator will do the work, but when I print both of the values to console like this:
Console.WriteLine((int)MyEnum.All);
Console.WriteLine((int)MyEnum.Unknown);
it prints -1
and -1
.
What am I doing wrong and how can I modify the code to have Unknown
right before All
?
Edit: thanks to everyone for the asnwers, I overlooked that the right-shift operator performs arithmetic shift and "propagates the sign bit to the high-order empty bit positions". In the end I realized that my approach would give me wrong results anyway because MyEnum.Unknown.HasFlag(MyEnum.First);
would return true and that would be incorrect behavior. This answer pointed me to the right direction and I set Unknown
to int.MinValue
and that is excatly what I wanted to accomplish - I wanted Unknown
to be like any other value and also be the highest possible one. Now Im just embarrassed that I did not think about that earlier...