How to get an Enum from a String in C#

By FoxLearn 12/26/2024 7:41:57 AM   83
In this tutorial, we’ll demonstrate how to convert an enum from a string value in C#.

First, We will create a generic method to handle the conversion. This method will allow us to convert any enum type from a string, simplifying the process.

public static T StringToEnum<T>(string name)
{
    return (T)Enum.Parse(typeof(T), name);
}

With the Enum.Parse method, we can easily convert a string to an enum value. Since Parse returns an object, we need to cast it to the desired enum type.

For example:

public enum Seasons
{
    Spring,
    Summer,
    Fall,
    Winter
}

public enum Colors
{
    Red,
    Blue,
    Green,
    Yellow,
    Black,
    White
}

Converting from a string to an enum

Seasons season = StringToEnum<Seasons>("Summer");
// season is now Seasons.Summer

Colors color = StringToEnum<Colors>("Red");
// color is now Colors.Red

Handling an invalid string

What happens if we try to convert a string that doesn’t exist in the enum?

In that case, Enum.Parse will throw an ArgumentException.

Seasons season = StringToEnum<Seasons>("Autumn");
// Throws ArgumentException
// Requested value "Autumn" was not found.

To avoid the exception, we can first check if the string is a valid enum value using Enum.IsDefined. This method verifies if the provided string matches any of the enum names.

if (Enum.IsDefined(typeof(Seasons), "Autumn"))
{
    StringToEnum<Seasons>("Autumn");
}
else
{
    Console.WriteLine("Invalid enum value.");
}
// Output: Invalid enum value.