How do Nullable Value Types work?

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.

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.

System.DateTime 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>.

System.Nullable<T>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:

.NET Reflector

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.


Readonly vs. Const Keyword

I recently started my 'Know Your Framework' series with a post about the GetType() method vs. the is keyword. Today I want to talk about the readonly vs. the const keyword. Although they might seem to perform the same functionality they have a few important differences (Yes, just like GetType vs. is - it appears there is a reason they both exist Tongue out)

First let's take a look at how you would declare either a readonly or a const variable (hm, that sounds weird a constant variable?).

public const string MostCertainlyTrue = "Stephan is cool";
public readonly string AlsoVeryTrue = "C# is cool";

Note that the const variable must be initialized at the time of declaration, while the readonly variable can be assigned either at declaration or in a constructor. However readonly variables can only be assigned to once at runtime. Another difference is that const values are evaluated at compile-time and readonly variables at runtime. Lets have a look at some examples to make things more clear.

public class CoolClass
{
    public readonly int x = 25; // Initialize readonly field
    public readonly int y;
    public const int z = 1;

    public CoolClass()
    {
        y = 50; // Initialize readonly field through constructor
} public CoolClass(int value, int value2) { x = value; // Initialize readonly field through constructor y = value2; // Initialize readonly field through constructor } } class Program { static void Main() { CoolClass c = new CoolClass(); Console.WriteLine(c.x); // Writes 25 to Console Console.WriteLine(c.y); // Writes 50 to Console CoolClass cc = new CoolClass(10000, 20000); Console.WriteLine(cc.x); // Writes 10000 to Console Console.WriteLine(cc.y); // Writes 20000 to Console cc.x = 99; // This results in compile error
        CoolClass.z = 99; // This results in compile error
    }
}

As you can see, the results are as expected. The compiler is smart enough to let you know when you try to assign a value to a readonly variable, because that can really only be done either at declaration or in the constructor of the type (or static constructor of a static type).

In the sample above the const variable is set to a value of 1. const variables are not instance variables, which means you can access them through the type itself, in the previous example 'CoolClass.x', and can never be changed in runtime.


GetType() vs. is Keyword

Some time ago I posted about me putting up a series of blog posts about 'Know Your Framework' where in each post I would explain some class or construct in more detail. I've been fairly busy since, but here goes the first (simple) one:

You've probably at one time had to check the type of some object in your code. In C# there are two ways to do this, which at first eye seem to do the exact same thing. However they're not, and the difference is quite subtle.

GetType() is a method inherited from the Object base class, which returns the exact type of the instance you're calling it on. So lets look at the following example:

 
class Program
{
    static void Main()
    {
        foo foo = new foo();
        foo bar = new bar();

        Console.WriteLine(bar is foo);                            // Outputs True
        Console.WriteLine(bar.GetType() == foo.GetType());        // Outputs False
        Console.WriteLine(bar.GetType() == typeof(foo));        // Outputs False
    }
}

class foo { }

class bar : foo { }

The reason for this result is that GetType() returns the actual Type of the object in runtime whereas the is keyword checks whether the object can be successfully casted to the given type without an InvalidCastException being raised. In other words, when using the is keyword, the runtime checks whether the object CAN be of the type you're evaluating against.


"Know Your Framework" Series

Hi There,

In my endless quest to learn new stuff I'm thinking about starting a series of Know Your Framework. The goal of the series will be to investigate a random class from the .NET framework. I'll try to pick the more exotic classes which aren't often described and you might not know about.

I probably won't be posting this series on a regular basis, more like when I feel like it Wink. So I don't know yet when I'll start this series and which class is the first candidate. I just thought this would be cool so please bear with me.

PS. Please let me know what you think about this or if you have any classes already I could investigate please comment on this post.