How do nullable types work in C#?

? wraps the value type (T) in a Nullable<T> struct:

http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx


In addition to "int?" being a shortcut for "Nullable", there was also infrastructure put into the CLR in order to implicitly and silently convert between "int?" and "int". This also means that any boxing operation will implicitly box the actual value (i.e., it's impossible to box Nullable as Nullable, it always results in either the boxed value of T or a null object).

I ran into many of these issues when trying to create Nullable when you don't know T at compile time (you only know it at runtime). http://bradwilson.typepad.com/blog/2008/07/creating-nullab.html


For one of the better "behind the scenes" discussions about Nullable types you should look at CLR Via C# by Jeffrey Richter.

The whole of Chapter 18 is devoted to discussing in detail Nullable types. This book is also excellent for many other areas of the .NET CLR internals.

Tags:

C#