Most of the time when writing C# programs we use the short-circuiting conditional operators. These operators do not continue evaluation once the outcome has been determined.
Take this code:
bool b = false && CheckName(name);
b = false & CheckName(name);
Here we’re performing a logical AND with the value false and the result of the CheckName method. Because we have a false, the logical AND can never be true.
The first statement using the short-circuiting AND operator (“&&”) will not execute the CheckName method because as soon as it’s determined the outcome (the first value is false and we are AND-ing) the remaining terms are not even evaluated.
The second statement using the non-short-circuiting AND operator (“&”) will execute the CheckName method, even though the first value is false.
If we need to rely on the CheckName method always being called then we’d have to use the non-short-circuiting version; though writing code that relies on these kind of side effects is not usually a good idea.
The conditional OR operator also comes in two versions: non-short-circuiting (“|”) and short-circuiting (“||”).
If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.