Check that integer type belongs to enum member

Use Enum.IsDefined

Enum.IsDefined(typeof(Enum1), 4) == true

but

Enum.IsDefined(typeof(Enum1), 1) == false

As Sam says, you can use IsDefined. This is somewhat awkward though. You may want to look at my Unconstrained Melody library which would let you us:

Enum1 e2 = (Enum1)10;
if (e2.IsNamedValue()) // Will return false
{
}

It's probably not worth it for a single enum call, but if you're doing a lot of stuff with enums you may find some useful things in there.

It should be quicker than Enum.IsDefined btw. It only does a linear scan at the moment, but let me know if you need that to be improved :) (Most enums are small enough that they probably wouldn't benefit from a HashSet, but we could do a binary search...)

Tags:

C#