More Ado About Nothing (and VB 2005)

I grew up in a world in which you could only set reference types to Nothing. Attempting to set an integer to Nothing would cause a compile-time error. Not so, in Visual Basic 2005 (and maybe 2003 -- I never tried it). I never tried it 'cause, well, I assumed it would fail. On the other hand, when you set an integer to Nothing like this:

Dim i as Integer = Nothing
Debug.WriteLine(i.ToString())

what's actually happening is that you're assigning 0 to i. Not only does running the code here produce 0 in its output, but if you look at the IL for the code, in ILDASM, what you find is this:

  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldloca.s   i
  IL_0005:  call       instance string [mscorlib]System.Int32::ToString()
  IL_000a:  call       void [System]System.Diagnostics.Debug::WriteLine(string)

The first line of code creates a literal value 0, which gets assigned into the integer. I changed the code so that it explicitly assigned 0 to the integer, and the IL was exactly the same.

It turns out that assigning Nothing to a value type simply assigns the type's default value. I thank Herfried K. Wagner for this tip, and Jaoa Cardoso for the reference to the corresponding documentation, which states this fact explicitly. I had certainly missed it. Perhaps you had too.

Published Friday, April 21, 2006 8:00 AM by KenG
Filed under:

Comments

No Comments