Making values nullable

A04C0009 First, a little history lesson.

When .NET was first released, we had value types and object types.  The difference between the two is that you do not have to set aside memory for a value type because the memory is placed on the stack.  So ints, doubles, and structures are all value types.

However, even though the value type is treated differently, it is still ultimately inherited from the Object type.  This is good because it allows us to create a method

public void Foo(object o)
{
}

that an integer can be passed to

Foo(1);

But, what happens when we have a method we want to pass an integer to but if a value has never been assigned to it, we just want to ignore it?

In the old days, we’d have to write our function like this:

public void Foo(object o)
{

    if (o != null)
    {
        int realValue = (int)o;
        // do something real here.
    }
}

Of course, we’d need to add some extra code to verify that o really was an integer before we attempted to cast it to an int.  Not exactly “type safe.”

So an extension to the language was added that allows us to make values nullable.  By simply placing a question mark after the type declaration, we can assign a null value and our method allows us to have both a strongly typed parameter and the ability to make it null.

public void Foo(int? o)
{
    if (o != null)
    {
        // do something with o
    }
}

and we can call it like this:

int? i = 1;
Foo(i);

or if we don’t have a variable we are using, we can call it directly:

Foo(1);

Finally, if you have a variable of type int? that you need to pass to a parameter of type int, you’ll need to do some casting:

Here’s the method that is expecting an int:

public void Foo(int o)
{
}

and here is how you would cast it if the variable is an int?

int? i = 1;
Foo((int)i);

If you are working the other way around, you do not need to provide any casting operators.

Related Post

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear