Search code examples
c#language-featuresconditional-statements

Merging nested If in C# (Short Circuit Keywords in C#)


Is it possible to merge the following statement:

if (a != null)
{
  if (a.Count > 5)
  {
     // Do some stuff
  }
}  

to just 1 If statement and make it not to check the second condition when the first one is not satisfied. (like AndAlso keyword in VB.NET). something like:

if (a != null /* if it is null, don't check the next statement */ &&& a.Count > 5)
{
   // Do some stuff
}

Solution

  • Simply:

    if ((a != null) && (a.Count > 5)) {
        // ...
    }
    

    In C#, the && operator short-circuits, meaning it only evaluates the right-hand expression if the left-hand expression is true (like VB.NET's AndElse).

    The And keyword you are used to in VB.NET does not short-circuit, and is equivalent to C#'s & (bitwise-and) operator.

    (Similarly, || also short-circuits in C#, and VB.NET's Or is like C#'s |.)