Enum.TryParse<> unexpected behaviour

Check code below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace EnumTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TestEnum result;

            bool ret = Enum.TryParse<TestEnum>("Yellow", out result);
            // ret value becomes: false
 
            ret = Enum.TryParse<TestEnum>("111", out result);
            // ret value becomes: true, result becomes: 111 !!!!!
        }
    }
 
    enum TestEnum
    {
        Red = 1,
        Green = 2
    }
}

Something found in help:

“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. ”

Nice.

This entry was tagged , .

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.