C Sharp

How to convert a string to enum using C#

We can use the following methods to convert a string to Enum in C#

  • Enum.Parse()
  • Enum.TryParse()

The difference between the two methods is that Enum.Parse() will throw an exception if it cannot convert a string to Enum while Enum.TryParse() returns boolean false if it cannot convert the string to Enum.

Let’s see the usage of both these methods below:

Enum.Parse()

// Define Enum - Car
enum Car { Tesla, Ford, Honda };

// Try to parse "Tesla"
try
{
Car TestCar = (Car)Enum.Parse(typeof(Car), "Tesla");
Console.WriteLine(TestCar.toString());
}
catch (Exception ex)
{
Console.WriteLine("We will not reach here since Tesla exists in Car Enum.");
}

Output: "Tesla"

// Try to parse "Toyota"
try
{
Car TestCar = (Car)Enum.Parse(typeof(Car), "Toyota");
Console.WriteLine(TestCar.toString());
}
catch (Exception ex)
{
Console.WriteLine("We will reach here since Toyota does not exists in Car Enum.");
}

Output: "We will reach here since Toyota does not exists in Car Enum."

Enum.TryParse()

// Define Enum - Car
enum Car { Tesla, Ford, Honda };

// Try to parse "Tesla"

Car TestCar;
Enum.TryParse("Tesla", out TestCar);
Console.WriteLine(TestCar.toString());

Output: "Tesla"

// Try to parse "Toyota"

Car TestCar;
Enum.TryParse("Toyota", out TestCar);
Console.WriteLine(TestCar.toString());


Output: "false"

Leave a Reply