Advertisement
Beginner C#, Enums & Flags

How do you convert between an enum value and its underlying numeric value, and between an enum and its string name?

Short answer

Cast directly with (int) to get the numeric value; use ToString() to get the member's name as a string, and Enum.Parse () (or the safer Enum.TryParse ()) to convert a string back into the corresponding enum value.

Save C# mock interview
Advertisement
AModel answer
Cast directly with (int) to get the numeric value; use ToString() to get the member's name as a string, and Enum.Parse<T>() (or the safer Enum.TryParse<T>()) to convert a string back into the corresponding enum value.
DayOfWeek day = DayOfWeek.Monday;
int numericValue = (int)day;          // 1
string name = day.ToString();          // "Monday"
DayOfWeek parsed = Enum.Parse<DayOfWeek>("Tuesday"); // DayOfWeek.Tuesday
Real-world example
Converting a user-selected string from a dropdown into the corresponding enum value for use in business logic.
Likely follow-ups
  • What exception does Enum.Parse<T>() throw if the input string doesn't match any enum member, and how does TryParse avoid it?
Related topics