CodeBlanks Logo Icon CodeBlanks

Flags attribute

C# course · Beginner · Lesson 104/116

Learn to create bit-based combinations with [Flags].

Bit fields with [Flags]

The [Flags] attribute lets an enum represent combinations of bit fields. A single variable can then hold several values at once. It is ideal for file permissions, option flags, or day combinations.

Declaration: [Flags] enum Perm { Read = 1, Write = 2, Exec = 4 }. Make sure the values are powers of two, so each flag occupies its own bit and bitwise operations can combine them. The [Flags] attribute only prettifies the ToString output; it does not change behaviour.

Combining with bitwise OR

To combine two or more flags, use the bitwise OR operator |. The result is a new value that holds the bits of each flag. This is the standard way to represent multiple permissions or options in a single variable.

For example, Perm p = Perm.Read | Perm.Write; assigns both read and write permissions to p. (int)p gives 3. Thanks to [Flags], calling p.ToString() returns a readable result like "Read, Write".

Querying with HasFlag

To check whether a specific flag is set in a combined flag value, use the HasFlag method. It returns a bool that is true when the queried flag is set.

For example, p.HasFlag(Perm.Read) returns true if p includes the read flag. Alternatively, you can write (p & Perm.Read) != 0, which uses bitwise AND to check the flag. Both approaches are common.

Exercise Combine permissions and print

Define a [Flags] enum called Perm with members Read = 1, Write = 2, Exec = 4. In Main, combine the two flags as Perm p = Perm.Read | Perm.Write; and print (int)p with Console.WriteLine.

Show example solution
Define [Flags] enum Perm { Read = 1, Write = 2, Exec = 4 }, then add Perm p = Perm.Read | Perm.Write; and Console.WriteLine((int)p);
Example solution:
using System;

[Flags]
enum Perm { Read = 1, Write = 2, Exec = 4 }

class Program
{
    static void Main()
    {
        Perm p = Perm.Read | Perm.Write;
        Console.WriteLine((int)p);
    }
}

Test yourself

  1. What does Perm.Read | Perm.Write give?

    [Flags] enum Perm { Read = 1, Write = 2, Exec = 4 }
    • 1
    • 2
    • 3
    • 7
    Show answer

    3 — Correct! 1 | 2 = 3; bitwise OR combines the flags.

  2. Combine the flags

    Perm p = Perm.Read ____ Perm.Write;
    Show answer
    Perm p = Perm.Read | Perm.Write;
  3. Match the operation with its result

    Read | Write
    3
    HasFlag(Read)
    true/false
    Read & Write
    0

All lessons in Beginner