C#.NET Enums and reflection: what will this program print for the first enum name? enum color { red, green, blue } color c = color.red; Type t; t = c.GetType(); string[] str; str = Enum.GetNames(t); Console.WriteLine(str[0]);

Difficulty: Easy

Correct Answer: red

Explanation:


Introduction / Context:
This question tests understanding of C#.NET enumerations (enum) and the reflection-based helper methods on the System.Enum class, specifically Enum.GetNames(Type). It also touches on how enum member names and their underlying integer values are different concepts.



Given Data / Assumptions:

  • An enum named color is declared with members red, green, and blue.
  • A variable c of type color is assigned color.red.
  • t = c.GetType() obtains the runtime type of the enum instance.
  • Enum.GetNames(t) returns an array of the enum member names as strings in declaration order.
  • Console.WriteLine(str[0]) prints the first name in that array.


Concept / Approach:
For any enum type, Enum.GetNames returns a string array of the symbolic names in the order they are defined in code. Index 0 will therefore be the first declared name. Numeric values are not returned by GetNames; you would use GetValues or casts for underlying integral values.



Step-by-Step Solution:

The declared order is: red, green, blue.Calling Enum.GetNames(typeof(color)) returns { "red", "green", "blue" }.Therefore, str[0] is "red".


Verification / Alternative check:
You can print all names using a loop over Enum.GetNames(typeof(color)). You can also verify the underlying values with Enum.GetValues(typeof(color)) which by default are 0, 1, 2.



Why Other Options Are Wrong:
0, 1, and -1 are integers, not names returned by GetNames. color.red is the fully qualified enum field, not the string name produced by GetNames.



Common Pitfalls:
Confusing enum names (strings) with their underlying numeric values. Also, assuming GetNames returns numeric strings; it does not.



Final Answer:
red

Discussion & Comments

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