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