Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.TryParse strange behaviour

Tags:

c#

.net

enums

Why does this test pass? TestEnum doesn't contain and option with value "5". So this test should fail, but it doesn't.

        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);
        }
like image 271
Dmitry Khryukin Avatar asked Aug 14 '14 06:08

Dmitry Khryukin


2 Answers

Enum.TryParse Method (String, TEnum)

If value is a name that does not correspond to a named constant of TEnum, the method returns false. If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

"Returns an enumeration member whose underlying value is value converted to an integral type"
If the value is not present you get back the integer. I don't consider getting back 5 to be an "enumeration member" but that is how it works. If you parse 2 you get 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());
    }
}
like image 160
paparazzo Avatar answered Nov 15 '22 00:11

paparazzo


Use Enum.IsDefined(Type enumType,Object value) - Returns an indication whether a constant with a specified value exists in a specified enumeration.

MSDN: Enum.IsDefined Method

like image 26
SeeSharp Avatar answered Nov 15 '22 00:11

SeeSharp