5

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);
        }
5
  • Seems that the enum is flagged. 5 = 3+2 ... but i cant see any [Flags] attribute
    – S.L.
    Commented Aug 14, 2014 at 6:05
  • 8
    Maybe read the documentation: " 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" (and note that this is also consistent with e.g. casting ints to enums - the value doesn't have to be a defined one) Commented Aug 14, 2014 at 6:06
  • 2
    @S.L.: Flags wouldn't mean that there'd be a 5 value... flags involves bitwise OR-ing, not addition.
    – Jon Skeet
    Commented Aug 14, 2014 at 6:09
  • @JonSkeet it is too early in the morning ... didnt notice that. Thanks for the advice
    – S.L.
    Commented Aug 14, 2014 at 6:11
  • @Damien_The_Unbeliever thanks for your help. maybe I'll read it:) Commented Aug 14, 2014 at 7:38

2 Answers 2

6

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.