While working with Enums there is often the requirement to convert string type to an enum type.We can convert string or numeric values to an enum using the Parse methods provided by the Enum class.
Converting string to Enum in C# using Parse methods
There are two versions of the parse methods ,generic and non generic.Lets see how we can use these methods
Parse method of Enum class
This method is non generic so it requires type casting as it returns object type.Also we need to pass the Type object as an argument to this method.This type object represents the type of the enum
public static object Parse(Type enumType, string value);
So if we define an Enum as:
Then we can use the following code to convert the string value to enum value
string manager = "Manager";
var employee = (EmployeeType)Enum.Parse(typeof(EmployeeType), manager);
if (employee == EmployeeType.Manager)
In the above code we are converting the value of the string manager to an EmployeeType enum.The value assigned to the manager string is Manager which is one of the enum values.The first parameter which we pass to the Parse method is the type of the enum to which we want to convert the string value.The second parameter is the actual string value which we want to convert.
As the return type is object so we need to cast it to the proper enum type.The output of the above conversion is an enum having value Manager.
TryParse method of Enum class
This is a generic method so it doesn’t require any type casting.This is an advantage of this method.
public static bool TryParse<TEnum>(string value, out TEnum result) where TEnum : struct
We can use this method as:
string value = "Normal";
Enum.TryParse<EmployeeType>(value, out employeeType);
if (employeeType == EmployeeType.Normal)
In the above code we are converting a string value to the same EmployeeType enum as in the previous example.But if you compare it with the previous example we are not using any casting ot type object.
If the type of the Enum can be inferred from the second parameter then we can omit the type argument of the TryParse method.
Converting string to enum in C# is easy using the static Parse methods of the Enum class.
For converting Enum to string refer :Convert Enum to String in C#