开发者

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 whe开发者_如何学Cn 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
}


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 |.)


if ((a != null) && (a.Count > 5)) // Parentheses are nice, but not necessary
{
  // Excitement goes here
}

In C#, && is indeed a "short circuit" operator — if the expression to its left is false, the expression to its right will not be evaluated.


You need the && operator to short-circuit the if statement:

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

So, if a is null then there is no need to evaluate the second condition for the if statement to return a value of false and therefore not execute the code in the block.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜