[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Use reflection to list the values defined by an enum in C#


Reflection is an advanced technique that lets a program query objects about themselves. For example, it lets you learn what properties, methods, and events an object provides. This example shows how you can use it to list the values defined by an enum.

The following GetEnumValues method returns a list of the values defined by an enum. The method is generic so it takes the enum's type as a parameter. (That'll make more sense shortly when you see an example.)

// Return a list of an enumerated type's values. private List GetEnumValues() { // Get the type's Type information. Type t_type = typeof(T); // Enumerate the Enum's fields. FieldInfo[] field_infos = t_type.GetFields(); // Loop over the fields. List results = new List(); foreach (FieldInfo field_info in field_infos) { // See if this is a literal value (set at compile time). if (field_info.IsLiteral) { // Add it. T value = (T)field_info.GetValue(null); results.Add(value); } } return results; }

The method gets the Type object corresponding to the enum type. It calls that object's GetFields method to get the fields that the type defines. It loops through them to find those that are literals. The literal fields are set at design time so they represent the enum's defined values. (Other fields could contain values set at run time and those do not represent the enum's values.)

When it finds a literal field value, the code adds it to the result list.

The following code shows how the program displays a list of the values defined by the HatchStyle enum.

// Display the names of the HatchStyle values. private void Form1_Load(object sender, EventArgs e) { List hatch_styles = GetEnumValues(); foreach (HatchStyle hatch_style in hatch_styles) { lstHatchStyles.Items.Add(hatch_style.ToString()); } }

This code calls GetEnumValues for the HatchStyle type and then loops through the returned values, adding each one's name to a ListBox.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.