How to Convert a String to an Enum in C#

Category > CSHARP || Published on : Monday, March 13, 2023 || Views: 289 || C# enum string Enum.Parse programming development.


In C#, enums are a powerful feature that allows you to define a set of named constants. Sometimes, you may need to convert a string to an enum in C#. This article will provide you with detailed guidance on how to convert a string to an enum in C# with example code.

In C#, enums are a powerful feature that allows you to define a set of named constants. They can be used to improve code readability and maintainability by making it easier to understand the intent of the code. Sometimes, you may need to convert a string to an enum in C#. In this article, we will explore how to convert a string to an enum in C# with example code.

First, let's define an enum for our examples:

public enum Fruit
{
    Apple,
    Banana,
    Mango,
    Orange
}

Now, let's say we have a string that represents a fruit name, and we want to convert it to the corresponding enum value. Here's how we can do it using the Enum.Parse method:

string fruitName = "Banana";
Fruit fruit = (Fruit)Enum.Parse(typeof(Fruit), fruitName);

In this example, we pass the typeof(Fruit) parameter to the Enum.Parse method to specify the type of the enum we want to parse the string into. We also pass the fruitName string as the second parameter to specify the value we want to parse.

If the fruitName string is not a valid value for the Fruit enum, a System.ArgumentException exception will be thrown. To handle this exception, we can wrap the Enum.Parse method in a try-catch block:

string fruitName = "Grapes";
Fruit fruit;

try
{
    fruit = (Fruit)Enum.Parse(typeof(Fruit), fruitName);
}
catch (ArgumentException)
{
    Console.WriteLine($"'{fruitName}' is not a valid fruit name.");
}

In this example, if the fruitName string is not a valid value for the Fruit enum, the catch block will execute and print an error message.

If you want to ignore case when parsing the string, you can pass the true value as the third parameter to the Enum.Parse method:

string fruitName = "mango";
Fruit fruit = (Fruit)Enum.Parse(typeof(Fruit), fruitName, true);

In this example, the string "mango" will be parsed to the Fruit.Mango value, even though the case of the string doesn't match the case of the enum value.

In conclusion, converting a string to an enum in C# is a straightforward process using the Enum.Parse method. By using enums in your code, you can make your code more readable and maintainable. It is important to handle exceptions when parsing a string to an enum to ensure that your code doesn't crash unexpectedly.