Search code examples
c#.netenumsenumerationtryparse

Enum Is Defined not giving value from Index


Dear Friends,

 public enum Units
    {
      Meter = 0,
      Centimeter = 1,
      Milimeter = 2
    }
    
    unitEnumStringOrIndex = "Meter"; //Working
    unitEnumStringOrIndex = "1";// Not working
    
    if(Enum.TryParse<Units>(unitEnumStringOrIndex, true, out Units unitEnum))
    {
      if(Enum.IsDefined(typeof(Units), unitEnumStringOrIndex))
        {
           return true;
        }else {
           return false;
        }
     }else {
      return false;
     }

I am having a strange problem as you can see from the above example. We have an enum type and we want to make sure that enum value exists.so for that I have read in Microsoft documentation that we can use IsDefined method to ensure existence. I implemented that and I can see that it returns the correct value when we pass the "Meter" string but similar way if I pass the "1" then it does not return true. So I do not return me the value Centimeter as expecting. Any lead will be appreciating. Thanks In Advance.


Solution

  • It's working just fine, only not as you're expecting.

    The TryParse method will succeed to parse the value whether it's a string containing the name of one of the enum's members, or a string that can be parsed as the value of one of the enum members.

    From official documentation:

    Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

    This means that when you try parse the string "Meter" the result is Units.Meter, but when you try parse the string "1" the result is Units.Centimeter.

    The IsDefined method is documented as follows:

    Returns a Boolean telling whether a given integral value, or its name as a string, exists in a specified enumeration.

    This means that if you feed it with "1" or 1 it does different things - the string does not match the name of any of the enum members and therefor IsDefined returns false, however the int does match the value of one of the enum members and therefor IsDefined returns true.

    You can see a live demo on rextester.