Enum.TryParse weird behavior

Why does this test pass? TestEnum does not contain a parameter with a value of "5". Thus, this test should fail, but it is not.

        private enum TestEnum
        {
            FirstOption = 2,
            SecontOption = 3
        }

        [Test]
        public void EnumTryParseIntValue()
        {
            TestEnum enumValue;

            bool result = Enum.TryParse<TestEnum>(5.ToString(), out enumValue);

            Assert.IsTrue(result);
        }
+4
source share
2 answers

Enum.TryParse Method (String, TEnum)

- , TEnum, false. , TEnum , , value - , . , IsDefined, , TEnum.

" , "
, . , 5 " ", . 2, FirstOption.

if (Enum.IsDefined(typeof(TestEnum), 5.ToString()))
{
    result = Enum.TryParse<TestEnum>(5.ToString(), out enumValue);
    Debug.WriteLine(result);
    if (result)
    {
        Debug.WriteLine(enumValue.ToString());
    }
}
+5

Enum.IsDefined(Type enumType, Object value) - , .

MSDN: Enum.IsDefined Method

+1

All Articles