Logic operator shortcut
In this chapter you will learn:
When to use Logic operator 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;//j a va 2 s .c om
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:
The & and | don't do the shortcut.
&& vs &
using System;/*ja v a2s.c o m*/
class MainClass
{
static bool Method1()
{
Console.WriteLine("Method1 called");
return false;
}
static bool Method2()
{
Console.WriteLine("Method2 called");
return true;
}
static void Main()
{
Console.WriteLine("regular AND:");
Console.WriteLine("result is {0}", Method1() & Method2());
Console.WriteLine("short-circuit AND:");
Console.WriteLine("result is {0}", Method1() && Method2());
}
}
Side-effects of short-circuit operators
using System; //from java 2 s . co m
class Example {
public static void Main() {
int i;
bool someCondition = false;
i = 0;
Console.WriteLine("i is still incremented even though the if statement fails.");
if(someCondition & (++i < 100))
Console.WriteLine("this won't be displayed");
Console.WriteLine("if statement executed: " + i); // displays 1
Console.WriteLine("i is not incremented because the short-circuit operator skips the increment.");
if(someCondition && (++i < 100))
Console.WriteLine("this won't be displayed");
Console.WriteLine("if statement executed: " + i); // still 1 !!
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial »