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);

Difficulty: Easy

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:

  • red and green have no explicit values.
  • blue = 5 is explicit.
  • cyan follows blue without an explicit value.
  • magenta = 10 is explicit, followed by yellow with 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

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion