Search code examples
c#nullable

whats the difference (if any) between nullable == null and nullable.hasvalue


Say I have

int? x = SomeFunc();

I got into the habit of saying

if(x != null && x.HasValue)
{
   // do somethign with x.Value;
}

But a code analysis tool headslapped me for doing this saying that the 2 conditions are the same. And I looked and in fact they are

ie if

int? x = null;
x==Null; // true
x.HasValue // false

So why 2 ways of testing for the same thing? Is there a subtle difference I am missing?


Solution

  • There is no difference between these two . it's just matter of convention .

    Just pick one (which you like) and stick with it .