Validate Enum Values

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)

Leave a Comment