Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if at least one enum value is equal to a variable within an if condition

Tags:

c#

enums

The common way of checking equality on multiple variables within an if condition is as following.

public enum Values
{
    Value1,
    Value2,
    Value3
}
void MethodName (Values randomValue )
{
 if (randomValue == Values.Value1|| randomValue == Values.Value2)
  {
       // code here
  }
}

Rather than having an OR condition, is there a better way of doing this ?

like image 521
Nilaksha Perera Avatar asked May 31 '16 03:05

Nilaksha Perera


People also ask

Can you use == for enum?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

How do you check if an enum is equal?

equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.

Can enum elements have same value?

CA1069: Enums should not have duplicate values.


1 Answers

A few options:

  1. You can define your enums as flags. This means each value must be a power of 2 (1, 2, 4, 8, etc). Then, you could write:

if (randomValue & (Values.Value1 | Values.Value2) > 0)
{
     //...
}
  1. You can use a switch

switch (randomValue)
{
    case Values.Value1:
    case Values.Value2:
    {
        //Do something
        break;
    }
    case Values.Value3:
        //Do something else
        break;
    default:
        break;
}
  1. You can use an array (nicer if you have predefined sets of values you want to search for).

if (new[] { Values.Value1, Values.Value2 }.Contains(randomValue))
{
}

or

static(?) readonly Values[] allowedValues = new[] { Values.Value1, Values.Value2 };

void MethodName(Values randomValue)
{
    if (allowedValues.Contains(randomValue))
    {
        //...
    }
}
like image 167
Rob Avatar answered Oct 15 '22 10:10

Rob