Use reflection to easily list the values defined by an enumerated type in C#

reflection

The example Use reflection to list the values defined by an enum in C# shows one way to list the values defined by an enumerated type. That method is flexible but somewhat awkward.

This example uses the first technique to display a list of enumerated values. Instead of getting the enum‘s type object and then digging through its fields to find those that are literals, this example uses the Enum class’s GetValues method to list the values defined by an enumeration. The GetValues method returns an array of values that the program can display by setting a ListBox‘s DataSource property.

This lets the program display the list with this single line of code:

lstValues.DataSource = Enum.GetValues(typeof(HatchStyle));

This is less flexible than the technique used by the previous example, but it’s much easier if you only want to list the values.


Download Example   Follow me on Twitter   RSS feed




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in enums, reflection, syntax and tagged , , , , , , , , , , . Bookmark the permalink.

One Response to Use reflection to easily list the values defined by an enumerated type in C#

  1. Pingback: Enumerate HatchStyle values and display samples of them in C# -

Leave a Reply

Your email address will not be published. Required fields are marked *