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 ?
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.
equals method uses == operator internally to check if two enum are equal. This means, You can compare Enum using both == and equals method.
CA1069: Enums should not have duplicate values.
A few options:
if (randomValue & (Values.Value1 | Values.Value2) > 0)
{
//...
}
switch (randomValue)
{
case Values.Value1:
case Values.Value2:
{
//Do something
break;
}
case Values.Value3:
//Do something else
break;
default:
break;
}
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))
{
//...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With