Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Nullable<T>.HasValue or Nullable<T> != 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)     // ... 

vs.

  1. int? b; if (b != null)     // ... 
like image 658
lc. Avatar asked Mar 24 '09 03:03

lc.


People also ask

What is HasValue?

HasValue indicates whether an instance of a nullable value type has a value of its underlying type. Nullable<T>. Value gets the value of an underlying type if HasValue is true . If HasValue is false , the Value property throws an InvalidOperationException.

What is null and nullable?

In C#, the compiler does not allow you to assign a null value to a variable. So, C# 2.0 provides a special feature to assign a null value to a variable that is known as the Nullable type. The Nullable type allows you to assign a null value to a variable.

What is nullable and non-nullable value type?

Nullable variables may either contain a valid value or they may not — in the latter case they are considered to be nil . Non-nullable variables must always contain a value and cannot be nil . In Oxygene (as in C# and Java), the default nullability of a variable is determined by its type.

What are the nullable types in C#?

A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value. The Nullable types are instances of System. Nullable<T> struct.


2 Answers

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.

like image 139
Rex M Avatar answered Oct 14 '22 01:10

Rex M


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

like image 29
cbp Avatar answered Oct 13 '22 23:10

cbp