CSharp - Nullable Type Operator Lifting

Introduction

When working with Nullable<T> struct C# uses(lift) the operator from the underlying value type

The following code compiles and executes correctly:

int? x = 5;
int? y = 10;
bool b = x < y;      // true

can be translated into this:

bool b = (x.HasValue && y.HasValue) ? (x.Value < y.Value) : false;

If both x and y have values, it compares via int's less-than operator; otherwise, it returns false:

The action of borrowing operator is called operator lifting.

Operator lifting ensures that you can implicitly use T's operators on T?.

Demo

using System;
class MainClass//from   w  ww.j ava  2  s  .  c om
{
   public static void Main(string[] args)
   {

         int? x = 5;
         int? y = null;

         // Equality operator examples
         Console.WriteLine (x == y);    // False
         Console.WriteLine (x == null); // False
         Console.WriteLine (x == 5);    // True
         Console.WriteLine (y == null); // True
         Console.WriteLine (y == 5);    // False
         Console.WriteLine (y != 5);    // True

         // Relational operator examples
         Console.WriteLine (x < 6);     // True
         Console.WriteLine (y < 6);     // False
         Console.WriteLine (y > 6);     // False

         // All other operator examples
         Console.WriteLine (x + 5);     // 10
         Console.WriteLine (x + y);     // null (prints empty line)
   }
}

Result