0

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?

pm100
  • 48,078
  • 23
  • 82
  • 145
  • 1
    I think you mean `x.HasValue // false` – userSteve Oct 25 '17 at 15:16
  • x==Null is wrong by OO concepts but it works as there is an exception for Nullable struct. Otherwise a struct in C# can never be null. so as a summary both work fine, but it's more correct, by Object Oriented definitions, to check HasValue. – Adel Tabareh Aug 22 '18 at 14:23

1 Answers1

1

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

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

Anwar Ul-haq
  • 1,851
  • 1
  • 16
  • 28
  • There is no difference between these .Above question already asked by few users on stackoverflow. http://stackoverflow.com/questions/17783929/c-sharp-hasvalue-vs-null – Anwar Ul-haq Feb 19 '16 at 21:35