CSharp - Operator Logic Operators

Introduction

The && and || operators test for and and or conditions.

! operator, which means not, negates the result.

We normally use logic operators to combine conditions.

In this example, the FieldTrip method returns true if it's rainy or sunny.

As long as it's not also windy:

bool FieldTrip (bool rainy, bool sunny, bool windy)
{
       return !windy && (rainy || sunny);
}

The && and || operators short-circuit evaluation.

In the preceding example, if it is windy, the expression (rainy || sunny) is not even evaluated.

Short-circuiting is useful in the following expressions.

if (sb != null && sb.Length > 0){
   
}

If the sb is null C# would not use its Length property which would avoid throwing a NullReferenceException.

The & and | operators test for and and or conditions:

return !windy & (rainy | sunny);

They are not short-circuit.

Exercise