ToEnum

        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);
        }
    }

Description

ToEnum - with nullable type

Details

  • Author: chris_mckelt
  • Submitted on: 1/23/2015 7:47:54 AM
  • Language: C#
  • Type: Enum
  • Views: 2074

Double click on the code to select all.

 

;