简体   繁体   中英

How to detect null comparisons with non-nullable variable types

Is there any way to detect this code snippet?

DateTime dt = DateTime.Now;
if (dt == null) {
    MessageBox.Show("Imposible with datetime!!!");
}

In our project we have detected that in Release compilation, the whole if gets removed because a comparison between a DateTime and null will be always false. I assume the optimizer translates it as:

if (false) { 
    ...
}

Is there any way to make the analyzer detect this code in any way? An error in compile time would be fine too, even if we have to create an FXCop rule, but we don't know how to track this case.

DateTime dt = null; // This code raises a compile time error, but the comparison with null is fine?

Similar to the IDE vein, ReSharper has support for catching this type of issue. It is a plugin to Visual Studio and we have found it very helpful over the years. It is still ahead of Microsoft in terms for refactoring features.

https://www.jetbrains.com/resharper/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM