Consider the following C# code that defines an enum and prints its underlying numeric value. What will be printed?
enum Color { Red = 1, Green = 2, Blue = 4 } class Program { static void Main() { Color c = Color.Blue; Console.WriteLine((int)c); } }
Look at the value assigned to Blue in the enum.
The enum Color assigns Blue the value 4 explicitly. Casting it to int prints 4.
Given this enum and code, what number is printed?
enum Status { Pending, Approved, Rejected } class Program { static void Main() { Status s = Status.Approved; Console.WriteLine((int)s); } }
Enums start numbering from 0 by default unless specified.
Pending is 0, Approved is 1, Rejected is 2. So Approved prints 1.
Analyze this code and determine the output printed.
enum Level { Low = 3, Medium, High = 10, Critical } class Program { static void Main() { Console.WriteLine((int)Level.Medium); Console.WriteLine((int)Level.Critical); } }
Implicit values increment from the previous value.
Medium is one more than Low (3), so 4. Critical is one more than High (10), so 11.
In C#, if you do not specify an underlying type for an enum, which numeric type does it use by default?
Think about the most common integer type in C#.
By default, enums use int as their underlying type unless specified otherwise.
Consider this enum with the [Flags] attribute and the code below. What will be printed?
[Flags] enum Permissions { None = 0, Read = 1, Write = 2, Execute = 4 } class Program { static void Main() { Permissions p = Permissions.Read | Permissions.Write; Console.WriteLine((int)p); } }
Bitwise OR combines the numeric values.
Read is 1, Write is 2. OR operation 1 | 2 = 3.