Easy way to check if a value is in an enum?

Hi,


I am trying to check if an int returned by the browser representing a user's account type is a valid value, ie. it is one of the values within an enumeration of valid account types.

Is there a quicker way of doing it than this


private bool InputIsWithinRange(ref int accountType)
{
Type accountTypeEnum_Type = typeof(SiteUser.AccountTypeEnum);

Array possibleValues = Enum.GetValues(accountTypeEnum_Type);

bool validAccountType = false;

for (int i = 0; i < possibleValues.Length; i++)
{
if (accountType == (int)possibleValues.GetValue(i))
{
validAccountType = true;
break;
}
}
return validAccountType;
}


Thanks!

Carlos




Answer this question

Easy way to check if a value is in an enum?

  • ajakeman

    hi pure sinewave

    Please mark replied, happy coding



  • BLACKDOG2

    You can do the following:

    return (Enum.GetName(SiteUser.AccountTypeEnum, (SiteUser.AccountTypeEnum)accountType) != null);


  • agni.yudha

    Chip Zero wrote:
    How about enum.IsDefined() It involves a boxing operation, but it's at least faster (and a lot shorter) than the implementation you gave above.

    hth,

    How stupid of me, you are indeed right.


  • Coeamyd

    How about enum.IsDefined() It involves a boxing operation, but it's at least faster (and a lot shorter) than the implementation you gave above.

    hth,


  • brase

    Brilliant, thanks very much guys. Much neater!



  • Easy way to check if a value is in an enum?