Search code examples
c#validationenums

Validate Enum Values


I need to validate an integer to know if is a valid enum value.

What is the best way to do this in C#?


Solution

  • You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!

    IsDefined is fine for most scenarios, you could start with:

    public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)
    {
     retVal = default(TEnum);
     bool success = Enum.IsDefined(typeof(TEnum), enumValue);
     if (success)
     {
      retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);
     }
     return success;
    }
    

    (Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension)