Matt Brailsford
Matt Brailsford

Reputation: 2237

Do C# enum flags have to be sequential

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

Answers (8)

Medeni Baykal
Medeni Baykal

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

Paul Nikonowicz
Paul Nikonowicz

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

Marlon
Marlon

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

Icarus
Icarus

Reputation: 63956

No, they don't have to be sequential. Compile your code and see it for yourself

Upvotes: 1

Sebastian Siek
Sebastian Siek

Reputation: 2075

They don't have to be sequential.

Upvotes: 4

Michal B.
Michal B.

Reputation: 5719

Yes, you can do that. It's up to you.

Upvotes: 3

Joe
Joe

Reputation: 42587

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

Upvotes: 4

Oded
Oded

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

Related Questions