To convert a string value to an enum value, use the Enum.TryParse function.
This is the enum we’ll use in the example code:
public enum Status { Waiting, InProcess, Completed = 42 }
Notice that the Completed value for the enum has an “= 42” after it.
Enums are like zero-based arrays. By default, the first enum option is number 0, the second is number 1, and so on. However, you can assign specific values to the options.
In the code below, we have a list of strings we’ll try to convert to their Status enum value.
List<string> testValues = new List<string> {"InProcess", "0", "42", "STARTING", "COMPLETED"}; foreach (string statusAsString in testValues) { if (Enum.TryParse(statusAsString, true, out Status statusFromString)) { Console.WriteLine($"Status: {statusFromString} - {Convert.ToInt32(statusFromString)}"); } else { Console.WriteLine($"'{statusAsString}' is not a valid enum value"); } }
On line 6, we use Enum.TryParse to attempt to convert the “statusAsString” value (first parameter) into the “statusFromString” variable (third parameter). The second parameter is a Boolean where we state if we want the conversion to ignore upper/lower differences when trying to find the matching enum option.
Enum.TryPrase will try to find the matching enum value by name or by number and returns a Boolean letting us know if it found a match.