lc. lc. - 1 year ago 80
C# Question

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

I always used (a)

because I liked the semantics. However, recently I was working on someone else's existing code base where they used (b)
Nullable<> != null
exclusively instead. Is there a reason to use one over the other, or is it purely preference?


int? a;
if (a.HasValue)


int? b;
if (b != null)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download