Which is preferred: Nullable.HasValue or Nullable != null?


I always used Nullable<>.HasValue because I liked the semantics. However, recently I was working on someone else's existing codebase where they used Nullable<> != null exclusively instead.

Is there a reason to use one over the other, or is it purely preference?

  1. int? a;
    if (a.HasValue)
        // ...


  1. int? b;
    if (b != null)
        // ...
3/8/2019 10:12:33 AM

Accepted Answer

The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.

3/24/2009 3:34:09 AM

I prefer (a != null) so that the syntax matches reference types.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow