Difficulty: Easy
Correct Answer: red
Explanation:
Introduction / Context:
Printing enum values in C# often surprises newcomers. Does it print the underlying number or the name?
Given Data / Assumptions:
color
has implicit underlying type int
with values red=0, green=1, blue=2.c
is assigned color.red
.
Concept / Approach:Console.WriteLine
calls ToString()
on the argument. Enum.ToString()
returns the named constant (e.g., "red"
) if it matches an exact named value. Therefore, the printed output is the name, not the numeric value.
Step-by-Step Solution:
c = color.red;
Print c
→ calls Enum.ToString()
→ returns "red"
.
Verification / Alternative check:
Cast to int
((int)c
) to print 0. Without the cast, the name is printed.
Why Other Options Are Wrong:1
or 0
would be printed only if explicitly cast. -1
is irrelevant. color.red
is not the string returned by ToString()
.
Common Pitfalls:
Assuming enums always print their numeric value.
Final Answer:
red
Discussion & Comments