diff --git a/PowerKit.Tests/Extensions/EnumExtensionsTests.cs b/PowerKit.Tests/Extensions/EnumExtensionsTests.cs new file mode 100644 index 0000000..6dffaf1 --- /dev/null +++ b/PowerKit.Tests/Extensions/EnumExtensionsTests.cs @@ -0,0 +1,37 @@ +using System; +using FluentAssertions; +using PowerKit.Extensions; +using Xunit; + +namespace PowerKit.Tests.Extensions; + +file enum TestEnum +{ + Foo, + Bar, +} + +public class EnumExtensionsTests +{ + [Fact] + public void ParseOrNull_Test() + { + // Act & assert + Enum.ParseOrNull("Foo").Should().Be(TestEnum.Foo); + Enum.ParseOrNull("foo").Should().BeNull(); + Enum.ParseOrNull("foo", true).Should().Be(TestEnum.Foo); + Enum.ParseOrNull("invalid").Should().BeNull(); + Enum.ParseOrNull(null).Should().BeNull(); + } + + [Fact] + public void ParseOrDefault_Test() + { + // Act & assert + Enum.ParseOrDefault("Foo").Should().Be(TestEnum.Foo); + Enum.ParseOrDefault("foo").Should().Be(default); + Enum.ParseOrDefault("foo", true).Should().Be(TestEnum.Foo); + Enum.ParseOrDefault("invalid", TestEnum.Bar).Should().Be(TestEnum.Bar); + Enum.ParseOrDefault(null, TestEnum.Bar).Should().Be(TestEnum.Bar); + } +} diff --git a/PowerKit/Extensions/EnumExtensions.cs b/PowerKit/Extensions/EnumExtensions.cs new file mode 100644 index 0000000..ad93617 --- /dev/null +++ b/PowerKit/Extensions/EnumExtensions.cs @@ -0,0 +1,47 @@ +#nullable enable +using System; +using System.Diagnostics.CodeAnalysis; + +namespace PowerKit.Extensions; + +#if !POWERKIT_INCLUDE_COVERAGE +[ExcludeFromCodeCoverage] +#endif +internal static class EnumExtensions +{ + extension(Enum) + { + /// + /// Parses the string as an enum value of type , + /// returning if parsing fails. + /// + public static TEnum? ParseOrNull(string? str, bool ignoreCase) + where TEnum : struct, Enum => + Enum.TryParse(str, ignoreCase, out var result) ? result : null; + + /// + /// Parses the string as an enum value of type , + /// returning if parsing fails. + /// + public static TEnum? ParseOrNull(string? str) + where TEnum : struct, Enum => Enum.ParseOrNull(str, false); + + /// + /// Parses the string as an enum value of type , + /// returning if parsing fails. + /// + public static TEnum ParseOrDefault( + string? str, + bool ignoreCase, + TEnum defaultValue = default + ) + where TEnum : struct, Enum => Enum.ParseOrNull(str, ignoreCase) ?? defaultValue; + + /// + /// Parses the string as an enum value of type , + /// returning if parsing fails. + /// + public static TEnum ParseOrDefault(string? str, TEnum defaultValue = default) + where TEnum : struct, Enum => Enum.ParseOrDefault(str, false, defaultValue); + } +}