Validate Enum Values

Jedi Master Spooky picture Jedi Master Spooky · Aug 17, 2008 · Viewed 55.7k times · Source

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

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

Answer

Vman picture Vman · Jan 26, 2011

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)