Condition with multiple logical operators on a single variable without repeating variable name

Viewed 125

Looking at the following if statement:

var veryLongVariableName = 7;
if (veryLongVariableName > 5 && veryLongVariableName < 18 && veryLongVariableName != 13)
{
    //do something...
}

Is there way to write this in a simpler way, so variable name would be not get repeated 3 times inside of if expression? I am looking for a solution that would also work for other value types/reference types.

1 Answers

If you're using C#9, you can use and:

var veryLongVariableName = 7;
if (veryLongVariableName is > 5 and < 18 and not 13)
{
    //do something...
}

Because you are checking against constant values, you can create a logical pattern, which uses is followed by and, or and not.

This also uses relational patterns (with the <, >, <= and >= operators); another C#9 pattern matching enhancement.

Related