I need to validate an integer to know if is a valid enum value.
What is the best way to do this in C#?
As others have mentioned, Enum.IsDefined is slow, something you have to be aware of if it's in a loop.
When doing multiple comparisons, a speedier method is to first put the values into a HashSet. Then simply use Contains to check whether the value is valid, like so:
int userInput = 4;
// below, Enum.GetValues converts enum to array. We then convert the array to hashset.
HashSet validVals = new HashSet((int[])Enum.GetValues(typeof(MyEnum)));
// the following could be in a loop, or do multiple comparisons, etc.
if (validVals.Contains(userInput))
{
// is valid
}