So in this post I want to talk about nullable value types. What are they? and why are they useful? So let's start with taking a look at the following code snippet.
At first it may not seem weird at all, however there is something going on in the background. Before you can totally understand what is going on you need to understand the difference between Value Types and Reference Types in the .NET Framework, which for now I'll suppose you do. If you declare a ValueType variable and suffix it with a question mark '?' you declare the type as being explicitly nullable.
If you take a look at the DateTime class in the Object Browser, you'll see that it derives from ValueType, which in turn derives from Object. But, as you may know ValueTypes cannot be null, so what is going on here?
What the compiler does at compile time is, it creates a generic variable of Nullable<T> where T is the type of the variable you declared. So in our case that would be Nullable<DateTime>.
But if we look at the Nullable<T> in the Object Browser we also see that it derives from ValueType, so how is all this possible. The answer is actually quite simple. If we take a look at the compiler generated code (with a tool called .NET Reflector) we'll see the following:
As you can see, the compiler translated our if(dt != null) check with if (dt.HasValue), and that is right where the answer is at. The Nullable<T> has a Value property which holds a reference to an object of the type you defined, or null.
So you can do dt.Value to access the object defined in the nullable type.
Now as to the why this might be a helpful feature, imagine you are using a database with Orders, now the Order type has a DeliveryDate, but you can imagine when a customer orders a product, it has to be shipped before it is delivered. So in the time between ordering and delivery the DeliveryDate should be something like null. With nullable value types this becomes possible, and allows for a much cleaner programming model.
posted by stephan on June 10, 2008 21:06
· Options