C# - How to convert/parse a string to an enum

Here is an example on how to parse a string to an enum using the built in enum.Parse method:


public enum Vehicle
{
    Car,
    Bus,
    Boat,
    Plane
}

var vehicle = (Vehicle)Enum.Parse(typeof(Vehicle), "Bus"); 

In the above I create an enum with four values that are all vehicles. I then call the enum.Parse method with the value "Bus" to get the Bus enum and store this in a vehicle variable. The other way around is much easier, you just call toString() to get the enum as a string!

Found this helpful? leave a comment down below.