Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C# enum flags have to be sequential

Tags:

c#

.net

enums

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
}
like image 908
Matt Brailsford Avatar asked Feb 07 '12 21:02

Matt Brailsford


People also ask

What is the do command in C?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

What is do loop in C?

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Do While vs while loop?

What is a do-while loop? The do-while loop is very similar to that of the while loop. But the only difference is that this loop checks for the conditions available after we check a statement. Thus, it is an example of a type of Exit Control Loop.


3 Answers

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...

like image 174
Oded Avatar answered Nov 07 '22 06:11

Oded


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.

like image 21
Marlon Avatar answered Nov 07 '22 07:11

Marlon


No such requirement. What you have is fine, assuming you capitalize [Flags].

like image 21
Joe Avatar answered Nov 07 '22 07:11

Joe