What is the output of this C# code that uses an enum to represent days?
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } class Program { static void Main() { Day today = Day.Wednesday; Console.WriteLine((int)today); } }
Remember enums start numbering from 0 by default.
Enums in C# assign integer values starting at 0 by default. Sunday is 0, Monday 1, Tuesday 2, Wednesday 3, so casting Day.Wednesday to int gives 3.
Why are enums preferred over using multiple constant values for related options?
Think about how enums help organize and check values in code.
Enums group related named constants under one type, making code easier to read and preventing invalid values by enforcing type safety.
What is the output of this C# code that sets an enum underlying type to byte?
enum Status : byte { Off = 0, On = 1, Unknown = 255 } class Program { static void Main() { Status s = Status.Unknown; Console.WriteLine((int)s); } }
Check the assigned value and how casting works.
The enum Status has underlying type byte. The value Unknown is assigned 255. Casting it to int prints 255.
What error occurs when running this C# code?
enum Color { Red, Green, Blue } class Program { static void Main() { Color c = 5; Console.WriteLine(c); } }
Check how enum variables are assigned values.
You cannot assign an int directly to an enum variable without casting. This causes a compile-time error.
Given this method that takes an enum parameter, what is the benefit of using an enum here?
enum Direction { North, East, South, West }
void Move(Direction dir) {
Console.WriteLine($"Moving {dir}");
}Think about how enums limit what values can be passed.
Using enums restricts the method input to predefined valid values, preventing mistakes and making the code easier to understand.