Conditional shortcut

shortcut means once the && or || knows the value of the whole bool expression, it stops the evaluation.

For example, a && b is false if a is false regardless whether b is true or false.

Under such condition C# doesn't execute b.

shortcut is useful in the following expression:

 
if(i != 0 && 4/i == 2)
  

If i is 0 C# won't calculate 4/i, which throws DivideByZeroException.

 
using System;

class Program
{
    static void Main(string[] args)
    {
        int i = 0;

        if (i != 0 && 4 / i == 2)
        {
            Console.WriteLine("here");
        }
        else {
            Console.WriteLine("there");
        }
    }
}
  

The output:


there

The & and | don't do the shortcut.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.