Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Flags attribute and bitwise enums in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flags Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of combined flags with bitwise OR
What is the output of this C# code using a Flags enum?
C Sharp (C#)
using System;

[Flags]
public enum Permissions
{
    None = 0,
    Read = 1,
    Write = 2,
    Execute = 4
}

class Program
{
    static void Main()
    {
        Permissions userPerms = Permissions.Read | Permissions.Write;
        Console.WriteLine(userPerms);
    }
}
A"Read"
B"Read, Write"
C"3"
D"Write"
Attempts:
2 left
💡 Hint
Look at how Flags attribute changes enum ToString output when combined with bitwise OR.
❓ Predict Output
intermediate
2:00remaining
Check if a flag is set using bitwise AND
What will this program print when checking if the Write flag is set?
C Sharp (C#)
using System;

[Flags]
public enum Access
{
    None = 0,
    Read = 1,
    Write = 2,
    Delete = 4
}

class Program
{
    static void Main()
    {
        Access rights = Access.Read | Access.Delete;
        bool canWrite = (rights & Access.Write) == Access.Write;
        Console.WriteLine(canWrite);
    }
}
ARuntime exception
BTrue
CCompile error
DFalse
Attempts:
2 left
💡 Hint
Bitwise AND with a flag returns the flag if set, otherwise zero.
❓ Predict Output
advanced
2:00remaining
Output of combined flags with overlapping values
What is the output of this code with overlapping enum values and Flags attribute?
C Sharp (C#)
using System;

[Flags]
public enum Options
{
    None = 0,
    Alpha = 1,
    Beta = 2,
    Gamma = 3
}

class Program
{
    static void Main()
    {
        Options opt = Options.Alpha | Options.Beta;
        Console.WriteLine(opt);
    }
}
A"Gamma"
B"Alpha"
C"Alpha, Beta"
D"3"
Attempts:
2 left
💡 Hint
Check the numeric values and how bitwise OR combines them.
❓ Predict Output
advanced
2:00remaining
Count how many flags are set in a Flags enum
What is the output of this program that counts set flags?
C Sharp (C#)
using System;

[Flags]
public enum Features
{
    None = 0,
    FeatureA = 1,
    FeatureB = 2,
    FeatureC = 4,
    FeatureD = 8
}

class Program
{
    static void Main()
    {
        Features enabled = Features.FeatureA | Features.FeatureC | Features.FeatureD;
        int count = 0;
        foreach (Features f in Enum.GetValues(typeof(Features)))
        {
            if (f != Features.None && (enabled & f) == f)
                count++;
        }
        Console.WriteLine(count);
    }
}
A3
B4
C2
D1
Attempts:
2 left
💡 Hint
Count how many individual flags are included in the combined value.
🧠 Conceptual
expert
2:00remaining
Why use powers of two in Flags enums?
Why must each flag in a Flags enum have a value that is a power of two?
ATo make the enum values easier to read as decimal numbers
BTo prevent the enum from being used in switch statements
CTo ensure each flag represents a unique bit so they can be combined without overlap
DTo allow the enum to be sorted alphabetically by value
Attempts:
2 left
💡 Hint
Think about how bits combine in binary when using bitwise OR.

Practice

(1/5)
1. What is the main purpose of the [Flags] attribute in C# enums?
easy
A. To allow combining multiple enum values using bitwise operations
B. To make enum values readonly
C. To automatically assign sequential integer values
D. To restrict enum values to a single choice only

Solution

  1. Step 1: Understand the role of [Flags]

    The [Flags] attribute marks an enum to be treated as a set of bit fields, allowing multiple values to be combined.
  2. Step 2: Compare with other options

    Options B, C, and D describe unrelated enum behaviors. Only To allow combining multiple enum values using bitwise operations correctly describes the bitwise combination feature.
  3. Final Answer:

    To allow combining multiple enum values using bitwise operations -> Option A
  4. Quick Check:

    [Flags] enables bitwise combination [OK]
Hint: Remember: [Flags] means combine enum values with bits [OK]
Common Mistakes:
  • Thinking [Flags] restricts enum to one value
  • Confusing [Flags] with readonly or sequential enums
  • Assuming [Flags] changes enum underlying type
2. Which of the following is the correct way to define a bitwise enum with the [Flags] attribute?
easy
A. [Flags] public enum Colors { Red = 0, Green = 1, Blue = 2 }
B. [Flags] public enum Colors { Red = 1, Green = 2, Blue = 4 }
C. public enum Colors { Red = 1, Green = 2, Blue = 3 }
D. [Flags] public enum Colors { Red = 1, Green = 1, Blue = 2 }

Solution

  1. Step 1: Check enum values for bitwise uniqueness

    Bitwise enums require values as powers of two (1, 2, 4, 8...) to avoid overlap.
  2. Step 2: Validate each option

    [Flags] public enum Colors { Red = 1, Green = 2, Blue = 4 } uses 1, 2, 4 which are correct powers of two. [Flags] public enum Colors { Red = 0, Green = 1, Blue = 2 } starts with 0 which is valid for None but not typical for flags representing colors. public enum Colors { Red = 1, Green = 2, Blue = 3 } uses 3 which overlaps bits. [Flags] public enum Colors { Red = 1, Green = 1, Blue = 2 } repeats 1 twice, causing overlap.
  3. Final Answer:

    [Flags] public enum Colors { Red = 1, Green = 2, Blue = 4 } -> Option B
  4. Quick Check:

    Enum values must be powers of two [OK]
Hint: Use powers of two for flags enum values [OK]
Common Mistakes:
  • Assigning zero to a flag value
  • Using overlapping values like 3 or repeated numbers
  • Forgetting the [Flags] attribute
3. Given the enum and code below, what is the output?
[Flags]
public enum Permissions { Read = 1, Write = 2, Execute = 4 }

Permissions userPerms = Permissions.Read | Permissions.Execute;
bool canWrite = (userPerms & Permissions.Write) == Permissions.Write;
Console.WriteLine(canWrite);
medium
A. True
B. Compile-time error
C. Runtime exception
D. False

Solution

  1. Step 1: Understand the combined flags

    The variable userPerms combines Read (1) and Execute (4) using bitwise OR, resulting in 5.
  2. Step 2: Check if Write flag is set

    The expression (userPerms & Permissions.Write) checks if Write (2) is set in 5. Since 5 & 2 = 0, it is not set, so canWrite is false.
  3. Final Answer:

    False -> Option D
  4. Quick Check:

    5 & 2 == 0 means Write not set [OK]
Hint: Check flags with AND (&) and compare to flag value [OK]
Common Mistakes:
  • Assuming OR sets all flags including Write
  • Confusing bitwise AND with OR
  • Expecting True because Write is in enum
4. Identify the error in the following code snippet using a [Flags] enum:
[Flags]
public enum Options { None = 0, First = 1, Second = 2, Third = 2 }

Options selected = Options.First | Options.Third;
Console.WriteLine(selected);
medium
A. Duplicate enum values cause overlapping flags
B. Missing [Flags] attribute
C. Bitwise OR operator is incorrect
D. Enum values must start from 1, not 0

Solution

  1. Step 1: Check enum value assignments

    Both Second and Third are assigned the value 2, causing overlap in flags.
  2. Step 2: Understand impact of duplicate values

    Duplicate values mean Options.Third is not unique, so bitwise operations may behave unexpectedly.
  3. Final Answer:

    Duplicate enum values cause overlapping flags -> Option A
  4. Quick Check:

    Enum values must be unique powers of two [OK]
Hint: Check for unique powers of two in enum values [OK]
Common Mistakes:
  • Ignoring duplicate values in flags enums
  • Thinking 0 is invalid for None
  • Assuming bitwise OR is wrong syntax
5. You have the following [Flags] enum:
[Flags]
public enum Features { None = 0, FeatureA = 1, FeatureB = 2, FeatureC = 4, FeatureD = 8 }
How would you write code to remove FeatureB from a variable currentFeatures that may contain multiple features combined?
hard
A. currentFeatures ^= Features.FeatureB;
B. currentFeatures |= Features.FeatureB;
C. currentFeatures &= ~Features.FeatureB;
D. currentFeatures = Features.FeatureB;

Solution

  1. Step 1: Understand how to remove a flag

    To remove a flag, use bitwise AND with the complement (NOT) of the flag.
  2. Step 2: Apply the operation to remove FeatureB

    The expression currentFeatures &= ~Features.FeatureB; clears the FeatureB bit while keeping others intact.
  3. Final Answer:

    currentFeatures &= ~Features.FeatureB; -> Option C
  4. Quick Check:

    Remove flag with AND and NOT [OK]
Hint: Remove flags with AND and NOT (~) operator [OK]
Common Mistakes:
  • Using OR (|) to remove flags instead of AND (&)
  • Assigning flag directly, overwriting all others
  • Using XOR (^) which toggles flags instead of removing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard