View Single Post
  #9 (permalink)  
Old April 18th, 2008, 04:06 AM
samjudson's Avatar
samjudson samjudson is offline
Friend of Wrox
Points: 8,687, Level: 40
Points: 8,687, Level: 40 Points: 8,687, Level: 40 Points: 8,687, Level: 40
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Aug 2007
Location: Newcastle, , United Kingdom.
Posts: 2,128
Thanks: 1
Thanked 189 Times in 188 Posts
Default

Both i.HasValue and i == null compile to exactly the same IL (i.HasValue).

Strangely a nullable type never seems to actually equal null.

i.e. The following throws a null reference exception:

List<int> l = null;
l.Add(1); // exception thrown

Nullable<int> i = null;
i.HasValue; // doesn't throw an exception, but returns false.

i = null actually compiles to a call to "initobj" IL command which initialises all the fields of the instance to null or zero.


/- Sam Judson : Wrox Technical Editor -/