ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ToEnum

ToEnum - with nullable type

Source

public static T? ToEnum<T>(this string value)where T : struct
{
    if (string.IsNullOrEmpty(value)) return default(T);
    T result;
    return Enum.TryParse<T>(value, true, out result) ? result : default(T);
}

Example

public class EnumExtensionsTestFixture
{
    private enum TestEnum
    {
        Abc,
        Xyz
    }

    [Fact]
    public void ToEnumShouldParseEqualString()
    {
        const string test = "Abc";
        TestEnum? result = test.ToEnum<TestEnum>();
        Assert.Equal(TestEnum.Abc, result);
    }

    [Fact]
    public void ToEnumShouldParseWrongCaseString()
    {
        const string test = "xyz";
        TestEnum? result = test.ToEnum<TestEnum>();
        Assert.Equal(TestEnum.Xyz, result);
    }

    [Fact]
    public void ToEnumShouldBeNullForInvalidString()
    {
        const string test = "lmn";
        TestEnum? result = test.ToEnum<TestEnum>();
        Assert.False(result.HasValue);
    }
}

Author: chris_mckelt

Submitted on: 23 jan. 2015

Language: C#

Type: Enum

Views: 7173