C#.NET enums with explicit and implicit values: what integers are printed? enum color : int { red, green, blue = 5, cyan, magenta = 10, yellow } Console.Write((int)color.green + ", "); Console.Write((int)color.yellow);
-
A2, 11
-
B1, 11
-
C2, 6
-
D1, 5
-
ENone of the above
Answer
Correct Answer: 1, 11
Explanation
Introduction / Context:This item checks your knowledge of how C#.NET assigns underlying integer values to enum members when some are explicit and others are implicit.
Given Data / Assumptions:
redandgreenhave no explicit values.blue = 5is explicit.cyanfollowsbluewithout an explicit value.magenta = 10is explicit, followed byyellowwith no explicit value.
Concept / Approach:Rules: the first unassigned enum member gets value 0; each subsequent unassigned member increases by 1 from the previous member’s value. When an explicit value appears, counting resumes from that value for subsequent unassigned members.
Step-by-Step Solution:
red → 0 (first implicit).green → 1 (implicit next).blue → 5 (explicit).cyan → 6 (implicit after 5).magenta → 10 (explicit).yellow → 11 (implicit after 10).Therefore, printing (int)color.green and (int)color.yellow yields 1, 11.Verification / Alternative check:Print all values via foreach (var x in Enum.GetValues(typeof(color))) Console.Write((int)x + " ");.
Why Other Options Are Wrong:2, 11 and 2, 6 mis-assign the early implicit values. 1, 5 uses yellow as 5, ignoring the explicit magenta = 10.
Common Pitfalls:Assuming implicit values reset after each explicit assignment or always start at 0 for each block; they continue from the last explicit value.
Final Answer:1, 11