Wrong compiler warning when comparing struct to null

谁说胖子不能爱 提交于 2019-11-30 18:12:24

You are correct: this is a bug in Visual Studio. The C# 4.0 standard (§ 7.3.7 Lifted operators) has this to say:

For the relational operators

<  >  <=  >=

[…] The lifted operator produces the value false if one or both operands are null.

And in fact, in MonoDevelop, you get the following warning instead:

The result of comparing type System.DateTime with null is always false.

I discovered this error independently while implementing lifted operator behaviour in Roslyn, and I fixed it in Roslyn before I left.

Sorry that I didn't see this when you posted it back in October. Thanks for submitting it to Connect! And many apologies for the error; it is a long-standing error in operator semantic analysis.

Incidentally, I'll be discussing how Roslyn optimizes lifted expressions on http://ericlippert.com later this month (December 2012), so if this subject interests you, check it out:

http://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/

awright18
DateTime t = DateTime.Today;

bool isGreater = (DateTime?)t > (DateTime?)null;

In this scenario what the warning is about is the t > null. That is never going to be true. Because It can't be evaluated.

In this scenario:

bool isGreater = (DateTime?)t > (DateTime?)null;

We are evaluating (DateTime?)t > (DateTime?)null;

Or essentially in the best case scenario t > null; same as before. DateTime.Now can never be greater than Undefined, hence the warning.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!