Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Problem in Parsing String Value to Enum Type

4.00/5 (1 vote)
2 May 2012CPOL 14.7K  
Problem in parsing string value in enum type

Today, I faced one issue with Enum.TryParse or Enum.Parse method. I was trying to parse string value to Enum but Enum.TryParse/Enum.Parse method was always giving true value for string which is not member of enum.

C#
public enum FieldAccessType
    {
        ReadOnly = 1,
        Add = 2,
        Modify = 4,
        AddModify = 6
    }

I want to convert string value, say “30″ to enum type that is not member of enum and conversion should fail, but I always get true value return enum.TryParse method which is surprising. I don’t know why it does not behave as per expectation.

C#
FieldAccessType type;
bool res=Enum.TryParse("20",out type );
Assert.IsFalse(res); //test is failing bcoz res is true

I found the MSDN documentation for Enum.TryParse/Enum.Parse and found the following lines:

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

Below is code which I corrected later:

C#
FieldAccessType fieldAccessType;
                    int intEnumValue;
                    if (Int32.TryParse(Value, out intEnumValue))
                    {
                        if (Enum.IsDefined(typeof (FieldAccessType), intEnumValue))
                            return (FieldAccessType) intEnumValue;
                    }

Enum.IsDefined to verify that the value you parsed actually exists in this particular enum.

I hope this trick will help you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)