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. You can also use it to list the values defined by an enum.

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

// Return a list of an enumerated type's values.
private List<T> GetEnumValues<T>()
{
// 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<T> results = new List<T>();
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 function 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. It calls GetEnumValues and then loops through the returned values, adding each one's name to a ListBox.

// 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());
}
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.