How to convert a string to enum in C#
In this tutorial, we are going to learn about how to convert a string to enum in C# with the help of examples
Using Enum.parse() method
To convert a string to enum, we can use the built-in Enum.parse()
method in C#.
The Enum.parse()
method takes the two arguments, the first one is enum type
and second one is string
then it converts to enum.
Here is an example:
using System;
class ConvertEnum {
enum Vehicle { Bus = 14, Lorry = 2, Car = 34 };
static void Main() {
Vehicle name= (Vehicle)Enum.Parse(typeof(Vehicle), "Bus");
System.Console.WriteLine(name);
}
}
Output:
Bus