From time to time I see an enum like the following:
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
I don't understand what exactly the [Flags]
-attribute does.
Anyone have a good explanation or example they could post?
@Nidonocu
To add another flag to an existing set of values, use the OR assignment operator.
I asked recently about something similar.
If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)
This allows you to do:
Then you can do:
I find this easier to read than the most ways of checking the included flags.
Please see the following for an example which shows the declaration and potential usage:
In extension to the accepted answer, in C#7 the enum flags can be written using binary literals:
I think this representation makes it clear how the flags work under the covers.
Flags allow you to use bitmasking inside your enumeration. This allows you to combine enumeration values, while retaining which ones are specified.