C# Conditional Operators

In this chapter you will learn:

  1. What are Conditional Operators
  2. Boolean logical AND operator
  3. Boolean logical OR operator
  4. Boolean logical NOT operator
  5. Logical operators with an if statement
  6. Short-circuit evaluation
  7. Not short-circuit
  8. When to use Logic operator shortcut
  9. && vs &
  10. Side-effects of short-circuit operators

Description

C# has the following conditional operators:

Operator Meaning
& AND
| OR
^XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! NOT

True table,

p Q p & qp | q p ^ q!p
FalseFalse False False False True
TrueFalse FalseTrue True False
False True False True True True
True TrueTrue True False False

AND operator

Boolean logical AND operator


class MainClass/* ww w .  j a  v  a2  s . c  o m*/
{

  public static void Main()
  {
    bool result;
    
    result = (1 == 1) && (2 > 1);
    System.Console.WriteLine("(1 == 1) && (2 > 1) is " + result);
    result = (1 == 1) && (2 < 1);
    System.Console.WriteLine("(1 == 1) && (2 < 1) is " + result);

  }

}

The code above generates the following result.

OR operator

Boolean logical OR operator


class MainClass// w w w  .j a v a2  s  . c om
{

  public static void Main()
  {
    bool result;
    
    
    result = (1 == 1) || (1 == 0);
    System.Console.WriteLine("(1 == 1) || (1 == 0) is " + result);
    result = (1 == 0) || (1 == 0);
    System.Console.WriteLine("(1 == 0) || (1 == 0) is " + result);
  }

}

The code above generates the following result.

NOT operator

Boolean logical NOT operator


// w  ww .ja v  a2s.co  m
class MainClass
{

  public static void Main()
  {
    bool result;
    
    
    result = !(1 == 0);
    System.Console.WriteLine("!(1 == 0) is " + result);
    result = !(1 == 1);
    System.Console.WriteLine("!(1 == 1) is " + result);
  }

}

The code above generates the following result.

Logical operators with an if statement

Logical operators with an if statement


class MainClass// w  ww  . ja  v a 2s.c  om
{

  public static void Main()
  {

    int intValue = 1500;
    string stringValue = "closed";

    if ((intValue > 1000) && (stringValue == "closed"))
    {
      System.Console.WriteLine("and");
    }
  }
}

The code above generates the following result.

Short-circuit evaluation

The && and || operators short-circuit evaluation when possible.

Shortcircuiting is essential in allowing expressions such as the following to run without throwing a NullReferenceException:


if (sb != null && sb.Length > 0){

}

Not short-circuit

The & and | operators test for and and or conditions as well:

The difference is that they do not short-circuit. For this reason, they are rarely used in place of conditional operators.

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;/*from ww  w  .  java2 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 &


/*  w w w . j  a  v  a2  s .  c  o m*/
using System;
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());
    }
}

The code above generates the following result.

Side-effects of short-circuit operators

Side-effects of short-circuit operators


using System; //from   w  w w . j a v a 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:

  1. ternary operator is if-then-else
  2. Syntax for ternary operator
  3. Example:Use ternary operator to get the bigger value
  4. Example:Use ternary operator in Console.WriteLine function
  5. Example:Prevent a division by zero
Home »
  C# Tutorial »
    C# Language »
      C# Operators
C# Arithmetic Operators
C# Arithmetic Assignment Operator
C# Increment and Decrement Operators
C# Remainder operator
C# Relational operators
C# Conditional Operators
C# Ternary operator(The ? Operator)
C# Bitwise Operators
C# Bitwise Shift Operators
C# sizeof Operator
C# typeof Operator