Posted by: Cirilo Meggiolaro | 11/20/2008

Tip of the day #37 – Safely casts for nullable types

Tip #36 explored the nullable types. Let’s take a look at how to perform safely casts when working with nullable types and avoid exceptions when accessing a nullable type value.

How to…

1. HasValue property

You may use the HasValue property to check if a nullable type contains any value before you access its value.

if (myNullBoolean.HasValue)
{
    // Do something
}

2. != operator

Another way to check if a nullable type contains any value is to use the != operator like the following code:

if (myNullBoolean != null)
{
    // Do something
}

3. Assign to non-nullable types

When you assign a nullable type to a non-nullable type you may use the ?? operator to determine a default value in case of a null value be the current value.

Nullable<bool> myNullBoolean;
bool myBool;

// Some code

myBool = myNullBoolean ?? false;

It’s really easy and straightforward to avoid exceptions when you read values from nullable types. If you have a way to do it, so you should do it.


Responses

  1. The third item here I´ve never seen!

    I particularly avoid using nullable types, but once I have made changes in one of my methods because I couldn´t do what you are showing here.

    Thanks!

  2. Hi Fadachi,

    The use of nullable types is very common when you work with any kind of mapping of your database tables to an object in your application for example if your application uses a table that has a column that accepts null values and you map it using LINQ or Entity Framework.

    I haven’t seen so much the use of the third item as well. It’s possible but is it useful? It depends on your application needs and a lot of programming tasks may be done in several different ways.

  3. Cirilo, based on the third tip, is there a way to make the opposite? Force an assignment from a non-nullable to a nullable?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: