Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c# - How do nullable types handle null values with comparison operators?

Does anyone have concrete information on how C# handles comparisons with Nullable<T> types when one side of the comparison is null?

As I understand from experimenting with the compiler, it seems that the comparison always returns false, but I can't find any documentation to back that up. Is this a real feature of the language (and thus something I can count on), or is this an implementation detail that might change in future versions?

In other words, does the following method returning true imply y.HasValue, and can you point me to some documentation that proves that it does?

    public bool foo(int x, int? y)
    {
        return x < y;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Does anyone have concrete information on how C# handles comparisons with Nullable types when one side of the comparison is null?

Yes - the C# language specification, section 7.3.7. In this case, it's a relational operator:

For the relation operators < > <= >= a lifted form of an operator exists if the operand types are both non-nullable types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator produces the value false if one or both operands are null. Otherwise, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.

There are similarly detailed sections for other operators.

When in doubt about how some aspect of the language works (and whether it's guaranteed or implementation-specific), the C# language specification should be your first port of call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...