Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

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