C# Conditional 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//  w  w  w . ja v  a 2  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  ava  2 s . co m*/
{

  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 w w  . j av  a 2s .  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  w w  .j a  va2  s. c  o m
{

  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;/* ww w  . j  av  a2s  .  com*/

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  .  jav  a2 s  . com
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; /*w w  w.  ja v  a 2  s. c  o  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.





















Home »
  C# Tutorial »
    C# Language »




C# Hello World
C# Operators
C# Statements
C# Exception