[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: Convert enum values to and from strings in C#

[Convert enum values to and from strings in C#]

The System.Enum class provides several methods that convert enum values to and from strings. Some particularly useful methods include:

GetNameReturns the string name of an enum value.
GetNamesReturns an array of strings holding the names of an enum's values.
GetValuesReturns an array an enum's values.
IsDefinedReturns true if a particular value is defined by an enum.
ParseParses a string and returns the corresponding enum value.

This example uses the following code to demonstrate the GetNames and Parse methods.

// The enumerated type. private enum MealType { Breakfast, Brunch, Lunch, Luncheon = Lunch, Tiffin = Lunch, Tea, Nuncheon = Tea, Dinner, Supper } // Convert values to and from strings. private void Form1_Load(object sender, EventArgs e) { foreach (string value in Enum.GetNames(typeof(MealType))) { // Get the enumeration's value. MealType meal = (MealType)Enum.Parse(typeof(MealType), value); // Display the values. lstStringValues.Items.Add((int)meal + "\t" + value); } }

The code uses Enum.GetNames to get strings representing the MealType values. For each of those strings, it uses Enum.Parse to convert the string into a MealType value. It then displays the value as an integer and in its string form.

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

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