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:
color
is declared with members red
, green
, and blue
.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:
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