Use C# 14 extensions to simplify enum Parsing

 
 
  • Gérald Barré

In .NET, many types provide a static Parse method to convert strings into their respective types. For example:

C#
int.Parse("123");
double.Parse("123.45");
DateTime.Parse("2023-01-01");
IPAddress.Parse("192.168.0.1");

However, enums require the use of the Enum.Parse method:

C#
Enum.Parse<MyEnum>("Value1");
// MyEnum.Parse("Value1"); // This doesn't work

Wouldn't it be more intuitive if enums supported a Parse method directly? With C# 14 and its new extension members feature, you can achieve this.

The following code demonstrates how to add Parse and TryParse methods to enums using C# 14 extensions:

EnumExtensions.cs (C#)
static class EnumExtensions
{
    extension<T>(T _) where T : struct, Enum
    {
        public static T Parse(string value)
            => Enum.Parse<T>(value);

        public static T Parse(string value, bool ignoreCase)
            => Enum.Parse<T>(value, ignoreCase);

        public static T Parse(ReadOnlySpan<char> value)
            => Enum.Parse<T>(value);

        public static T Parse(ReadOnlySpan<char> value, bool ignoreCase)
            => Enum.Parse<T>(value, ignoreCase);

        public static bool TryParse([NotNullWhen(true)] string? value, out T result)
            => Enum.TryParse(value, out result);

        public static bool TryParse([NotNullWhen(true)] string? value, bool ignoreCase, out T result)
            => Enum.TryParse(value, ignoreCase, out result);

        public static bool TryParse(ReadOnlySpan<char> value, out T result)
            => Enum.TryParse(value, out result);

        public static bool TryParse(ReadOnlySpan<char> value, bool ignoreCase, out T result)
            => Enum.TryParse(value, ignoreCase, out result);
    }
}

You can now use the Parse/TryParse method on the enum type itself, just like you would with other types.

C#
MyEnum.Parse("Value1");

if (MyEnum.TryParse("Value1", out var result))
{
    // Do something with the result
}

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub