CSharp - bool? with & and | Operators

Introduction

& and | operators on bool? type value treat null as an unknown value.

So, null | true is true, because:

  • If the unknown value is false, the result would be true.
  • If the unknown value is true, the result would be true.

null & false is false.

The following example enumerates other combinations:

Demo

using System;
class MainClass/*from w w w .jav  a  2 s .  com*/
{
   public static void Main(string[] args)
   {
         bool? n = null;
         bool? f = false;
         bool? t = true;
    
         Console.WriteLine (n | n);    // (null)
         Console.WriteLine (n | f);    // (null)
         Console.WriteLine (n | t);    // True
         Console.WriteLine (n & n);    // (null)
         Console.WriteLine (n & f);    // False
         Console.WriteLine (n & t);    // (null)
   }
}

Result

Related Topic