C# - What are Lifted operators?

Lifted operators work between value types and the nullable forms of those types.

Any operator that is valid on type T, will be lifted to work between T and Nullable<T>, or between Nullable<T> and Nullable<T>.

In plain english: You can add a Nullable<int> and Nullable<int> even though the Nullable class does not define a plus operator.


  int? ten = 10;
  int? twenty = 20;
  // result.Value is 30
  int? result = ten + twenty;

Without lifted operators, the compiler would report:
Error CS0019 Operator '+' cannot be applied to operands of type 'Nullable<int>' and 'Nullable<int>'.

You can confirm this by writing a MyNullable<T> class that is identical to Nullable (using the decompiled F12 metadata, or the .NET Reference Source).

In the above example, the C# compiler will lift the available plus operator, and rewrite the statement as follows:

  int? nullable1 = new int?(10);
  int? nullable2 = new int?(20);
  int? nullable3 = nullable1.HasValue & nullable2.HasValue ? new int?(nullable1.GetValueOrDefault() + nullable2.GetValueOrDefault()) : new int?();

Note that lifted operators are a feature of the compiler, and not of the runtime.

Finally, if either value is null, the result is null.

  int? ten = 10;
  int? twenty = null;
  // result is null
  int? result = ten + twenty;

Ads by Google

Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath