Convert String to Enum in C#

In C#, an enum is a value type that represents a set of named constants. To convert a string to an enum in C#, you can use any of the following methods:

Enum.Parse() method

The Enum.Parse method can be used to convert a string value to an enum. The method takes two arguments: the type of the enum and the string value to be parsed. If the string value is not a valid member of the enum, an exception is thrown.

using System; public class MyProgram { enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } public static void Main(string[] args) { string value = "Monday"; DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), value); Console.WriteLine(day + " "+ day.GetType()); Console.WriteLine(value + " " + value.GetType()); } }
//Output: Monday DayOfWeek Monday System.String

In the above example, the string value "Monday" is converted to the enum DaysOfWeek.

Enum.TryParse() method

The Enum.TryParse method can be used to convert a string value to an enum. The method takes three arguments: the type of the enum, the string value to be parsed, and an output parameter that receives the parsed enum value. If the string value is not a valid member of the enum, the output parameter is set to the default value of the enum and the method returns false.

using System; public class MyProgram { enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } public static void Main(string[] args) { string value = "Monday"; DayOfWeek day; if(Enum.TryParse<DayOfWeek>(value, out day)) { Console.WriteLine("Conversion succeeded"); } else { Console.WriteLine("Conversion failed"); } } }
//Output: Conversion succeeded

Enum in C#

In C#, an enum is a value type that represents a set of named constants. An enum can be defined as a distinct type or as a part of a class or structure. Each constant in an enum is assigned an underlying integral value, which can be either implicitly or explicitly defined.


How to convert string to enum in C#

Enums can be useful for defining a set of named values that are mutually exclusive, such as days of the week or colors. They make code more readable and less error-prone by providing a descriptive name for each value, rather than relying on a numeric or string representation.