tags:

views:

1699

answers:

3

I always used (a)Nullable<>.HasValue 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?

(a)

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

(b)

int? b;
if(b != null)
    ...
+19  A: 

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.

Rex M
I would add to that "whichever is more consistent/follows an existing coding style."
jleedev
+1  A: 

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

cbp
+1  A: 

In VB.Net. Do NOT use "IsNot Nothing" when you can use ".HasValue". I just solved an "Operation could destabilize the runtime" Medium trust error by replacing "IsNot Nothing" with ".HasValue" In one spot. I don't really understand why, but something is happening differently in the compiler. I would assume that "!= null" in C# may have the same issue.

Carter