Non Short Circuiting C# Conditional Operators

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 (“||”).

 

This is one feature (among others) that I cover in my Pluralsight C# Tips and Traps 2 course.

Comments (5) -

  • Darren Fieldhouse

    9/20/2013 8:05:36 PM | Reply

    It should also be pointed out that the & operator performs a bitwise AND, and the && performs a logical AND, which are not equivalent operations.

  • Zia

    9/23/2013 3:00:01 PM | Reply

    Your first b is boolean and second b is var. As I know you can perform bitwise on bool in c#. You may explain this also in this post

  • Ammar Shaukat

    7/8/2018 8:39:19 PM | Reply

    thanks for the nice share.

    • Jason

      7/10/2018 1:03:31 AM | Reply

      Thanks Ammar.

Pingbacks and trackbacks (1)+

Add comment

Loading