What are lifted operators?

折月煮酒 提交于 2019-11-26 17:23:36

Lifted operators are operators which work over nullable types by "lifting" the operators which already exist on the non-nullable form. So for example, if you do:

int? x = 10;
int? y = 10;
int? z = x + y;

That "+" operator is lifted. It doesn't actually exist on Nullable<int> but the C# compiler acts as if it does, generating code to do the right thing. (For the most case, that's a matter of checking whether either operand is null; if so, the result is null. Otherwise, unwrap both operands to their non-nullable values, use the normal operator, and then wrap the result back into a nullable value. There are a few special cases around comparisons though.)

See section 6.4.2 (lifted conversion operators) and 7.3.7 (lifted operators) of the C# spec for more information.

Lifted operators allow predefined and user-defined operators that work for non-nullable types to be used for their nullable forms as well.

int i = 5;
int? j = 6;

int? k = j + i;    // 11
int? q = i + null; // null - Shows a warning the result of the expression is always null of type int?
int r = i + null; // Throws an error the result of expression is always null of type int?
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!