Enum flags allow you to put multiple values in an enum variable/parameter. This is a nice alternative to the problem of having to pass around a ton of bools . You set multiple values by bitwise ORing them together. Here’s an example:
JsonOptions options = JsonOptions.PrettyPrint | JsonOptions.IgnoreNulls;
Code language: C# (cs)
In this article, I’ll show how to create and use enum flags.
Use [Flags] attribute on enum type
To enable an enum to have multiple values:
- Add the [Flags] attribute to the enum type.
- Set the enum integer values to powers of 2.
- Optionally add None=0 to mean no values are set.
Here’s an example:
[Flags]
public enum JsonOptions
{
None = 0,
PrettyPrint = 1,
UseEnumStrings = 2,
IgnoreNulls = 4,
CaseInsensitive = 8
}
Code language: C# (cs)
Note: This example enum abstracts JSON options, which is useful when you’re switching between JSON serializers.
The reason you have to use powers of 2 is because the enum values are bit positions in the enum’s binary representation. This makes more sense if you look at the literal binary values:
[Flags]
public enum JsonOptions
{
None = 0b0000, //0
PrettyPrint = 0b0001, //1
UseEnumStrings = 0b0010, //2
IgnoreNulls = 0b0100, //4
CaseInsensitive = 0b1000 //8
}
Code language: C# (cs)
Because each value is a bit position, bitwise ORing them together allows you to store multiple values at once. For example: JsonOptions.PrettyPrint | JsonOptions.IgnoreNulls is this binary operation:
0001
|
0100
-----
0101
Code language: plaintext (plaintext)
Use HasFlag() to check if a value is set
The simplest way to check if an enum has a specific value set, use HasFlag():
JsonOptions options = JsonOptions.PrettyPrint | JsonOptions.IgnoreNulls;
if (options.HasFlag(JsonOptions.PrettyPrint))
{
Console.WriteLine("Has PrettyPrint!");
}
if (options.HasFlag(JsonOptions.IgnoreNulls))
{
Console.WriteLine("Has IgnoreNulls!");
}
Code language: C# (cs)
This outputs:
Has PrettyPrint!
Has IgnoreNulls!
Code language: plaintext (plaintext)
Alternatively, you can check if a value is set by bitwise ANDing. You’d do that like this:
- (options & JsonOptions.PrettyPrint) == JsonOptions.PrettyPrint.
Using HasFlag() is simpler.
Set more values on the enum
As shown above, you can set values on the enum when you initialize it by bitwise ORing all the values together. Additionally, you can add more values to the enum at any point by bitwise ORing it with itself and the value. Here’s an example:
JsonOptions options = JsonOptions.PrettyPrint | JsonOptions.IgnoreNulls;
if (!options.HasFlag(JsonOptions.CaseInsensitive))
{
options |= JsonOptions.CaseInsensitive;
}
Console.WriteLine(options.ToString());
Code language: C# (cs)
This outputs the
PrettyPrint, IgnoreNulls, CaseInsensitive
Code language: plaintext (plaintext)