Sai A Sai A
Updated date Jun 22, 2023
In this blog, we will provide a comprehensive guide to converting a string to an enum in C#. It explores various methods, including Enum.Parse(), Enum.TryParse(), and custom mapping with a Dictionary.

Introduction:

In C#, enumerations (enums) are a powerful feature that allows developers to define a set of named constants. Enums provide better readability and type safety to your code, but there are instances when you need to convert a string representation of an enum value back to its corresponding enum value. This blog will explore various methods for converting strings to enums in C#, along with code examples and explanations.

Method 1: Enum.Parse()

The first method we'll explore is using the Enum.Parse() method, which is a built-in function in C#. It allows you to convert a string representation of an enum value into the corresponding enum value.

Here's an example that demonstrates the usage of Enum.Parse():

string input = "Monday";
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), input);
Console.WriteLine(day);

Output:

Monday

In the above code, we have a string input containing the value "Monday," which we want to convert to the DayOfWeek enum type. We use the Enum.Parse() method and pass the target enum type (DayOfWeek) and the input string. The method returns the corresponding enum value, which is then assigned to the day variable.

Method 2: Enum.TryParse()

Another approach to converting strings to enums is by using the Enum.TryParse() method. This method is useful when you want to handle potential parsing errors without throwing an exception.

Consider the following example:

string input = "Friday";
DayOfWeek day;
if (Enum.TryParse(input, out day))
{
    Console.WriteLine(day);
}
else
{
    Console.WriteLine("Invalid input");
}

Output:

Friday

In this code snippet, we use the Enum.TryParse() method, which takes the input string and an output parameter (day) that will store the parsed enum value if successful. If the parsing is successful, the method returns true, and we can access the parsed value in the day variable. Otherwise, if parsing fails, we can handle the error gracefully.

Method 3: Custom Mapping with Dictionary

If you have a more complex scenario where the string representation of the enum value does not match its name, you can use a custom mapping with a Dictionary<string, YourEnumType>.

Let's consider the following example:

enum Fruit
{
    [Description("Red Apple")]
    Apple,
    [Description("Yellow Banana")]
    Banana,
    [Description("Green Pear")]
    Pear
}

Dictionary<string, Fruit> fruitMapping = new Dictionary<string, Fruit>()
{
    { "Red Apple", Fruit.Apple },
    { "Yellow Banana", Fruit.Banana },
    { "Green Pear", Fruit.Pear }
};

string input = "Red Apple";
if (fruitMapping.TryGetValue(input, out Fruit fruit))
{
    Console.WriteLine(fruit);
}
else
{
    Console.WriteLine("Invalid input");
}

Output:

Apple

In this example, we have an enum called Fruit, which has different descriptions for its enum values. We create a Dictionary<string, Fruit> named fruitMapping that maps the string descriptions to their corresponding enum values. Using the TryGetValue() method, we retrieve the enum value based on the input string, handling any potential mapping errors.

Conclusion:

In this blog post, we explored various methods for converting strings to enums in C#. We started with the built-in Enum.Parse() method, which is suitable for straightforward conversions. Then, we learned about Enum.TryParse(), which provides a more error-safe approach. Finally, we covered a custom mapping approach using a Dictionary for complex scenarios. Depending on your specific requirements, you can choose the method that best suits your needs and ensures robust string-to-enum conversion in your C# applications.

Comments (0)

There are no comments. Be the first to comment!!!