Operator Lifting - CSharp Language Basics

CSharp examples for Language Basics:Nullable

Introduction

The Nullable<T> struct does not define operators such as <, >, or even ==.

Despite this, the following code compiles and executes correctly:

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

This works because the compiler "lifts," the less-than operator from the underlying value type.

Semantically, it translates the preceding comparison expression into this:

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

In other words, if both x and y have values, it compares via int's less-than operator; otherwise, it returns false.

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

Here are some examples:

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)

Related Tutorials