
Short-circuiting occurs in AND and OR operators. In the C# language these logical operators have a short-circuit mechanism. As soon as enough evaluations occur to make the expression's result known, no further evaluations occur. This provides an interesting opportunity for adjusting logic, reducing lines of code and improving performance.
The semantic definition of the programming language determines whether all parts of a boolean expression must be evaluated. Aho et al, p. 400

This example presents four different if-statements. The ReturnTrue() and ReturnFalse() methods are called in pairs: these methods report to the Console when called and also return the expected value. In the Main method, we can see that for if-statements 1 and 4, both ReturnTrue and ReturnFalse are evaluated. For the remaining two if-statements, only the first method is evaluated.
This C# example program uses short-circuit logic in an if-statement.
Program that demonstrates short-circuiting [C#]
using System;
class Program
{
static void Main()
{
Console.WriteLine(1);
if (ReturnTrue() &&
ReturnFalse())
{
}
Console.WriteLine(2);
if (ReturnFalse() &&
ReturnTrue())
{
}
Console.WriteLine(3);
if (ReturnTrue() ||
ReturnFalse())
{
}
Console.WriteLine(4);
if (ReturnFalse() ||
ReturnTrue())
{
}
}
static bool ReturnTrue()
{
Console.WriteLine("ReturnTrue");
return true;
}
static bool ReturnFalse()
{
Console.WriteLine("ReturnFalse");
return false;
}
}
Output
1
ReturnTrue
ReturnFalse
2
ReturnFalse
3
ReturnTrue
4
ReturnFalse
ReturnTrue
Performance characteristics. When fewer parts of the if-statement are evaluated, performance improves. This means statement 2 is faster to statement 1, while statement 3 is faster than statement 4. Assuming no side effects occur when these methods are called, the faster ordering can always replace the slower ordering.

Whether an expression using && or || can be short-circuited depends on the language's semantics. This is because side effects might occur in any part of the expression, even those that can be optimized out. In this case, a version of the program that evaluates all parts of the expression would have a different result than the optimized form. In the C# language, short-circuiting always occurs and thus the expression evaluation is terminated when its final result is known. Side effects are not considered.

We examined short-circuiting and boolean expressions in the C# language. While short-circuiting yields faster code, consideration of the side effects of sub-expressions must be taken into account. In certain cases, short-circuiting can lead to incorrect code if some side effects never occur. This problem will not present itself if you do not mutate data in the methods you call.
If Statement