C#.NET enums — what is printed by: enum color { red, green, blue } color c; c = color.red; Console.WriteLine(c);
-
A1
-
B-1
-
Cred
-
D0
-
Ecolor.red
Answer
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:
colorhas implicit underlying typeintwith values red=0, green=1, blue=2.- Variable
cis assignedcolor.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:
Assignc = 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