Reputation: 2237
In C#, do enum flags have to be sequential? or can you leave gaps? and still perform bit-wise comparisons? ie, can you do the following:
[Flags]
public enum MyEnum
{
None = 0,
IsStarred = 1,
IsDone = 128
}
Upvotes: 9
Views: 2762
Reputation: 4333
Squental enums dont need to have the Flags attribute. But it is a best practice. You can read more here: http://msdn.microsoft.com/en-us/library/ms229062.aspx
Upvotes: 0
Reputation: 3903
Not only can you do that, but you can also do this:
public enum MyEnum
{
None,
IsStarred,
IsDone = 128
}
or
public enum MyEnum
{
None = 5,
IsStarred,
IsDone = 128
}
here's a link to more examples: http://www.dotnetperls.com/enum
Upvotes: 1
Reputation: 20314
There is nothing wrong with the code you have posted. This is absolutely fine:
[Flags]
public enum MyEnum
{
None = 0,
IsStarred = 1,
IsDone = 128
}
And so is this:
[Flags]
public enum MyEnum
{
IsStarred = 1,
IsDone = 128
None = 0,
SomethingElse = 4,
}
Just remember that the FlagsAttribute
does not enforce your values to be bit masks.
Upvotes: 6
Reputation: 63956
No, they don't have to be sequential. Compile your code and see it for yourself
Upvotes: 1
Reputation: 42587
No such requirement. What you have is fine, assuming you capitalize [Flags]
.
Upvotes: 4
Reputation: 498914
There is nothing that requires them to be sequential.
Your enum definition is fine and will compile without issue.
The issue of readability and the principle of least astonishment, however have been greatly compromised...
Upvotes: 9