Modern C# · Lesson 11

Flags and explicit checks

Combine independent options and test whether one is present.

How it works

A flags enum uses separate bits to represent options that can coexist. Read is one and Write is two, so the bitwise OR combines them into a value containing both flags. The bitwise AND isolates the bit being tested. Comparing the isolated result with zero answers whether that flag is present. Use powers of two for independent flags and reserve zero for no options.

A flags value can still contain undefined bits after conversion from an integer, so validate untrusted inputs at a boundary. Do not use this representation for mutually exclusive states that cannot meaningfully coexist.

Add Share to the access value and predict both outputs. Then consider why a payment state such as Pending or Refunded would usually be a different kind of model.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var access = Access.Read | Access.Write;
Console.WriteLine((access & Access.Read) != 0);
Console.WriteLine((access & Access.Share) != 0);
[Flags] enum Access { None = 0, Read = 1, Write = 2, Share = 4 }

Expected output

True
False
Try this
Independent flags need independent bits.