Posted by: Cirilo Meggiolaro | 11/19/2008

Tip of the day #36 – Nullable types

Nullable types were integrated to the .NET framework 2.0 and have the main characteristic of encapsulate a value type in a System.Nullable structure, with a default null value while the object has not been initializated yet. The value ranges for numeric types for example will remain the same.

Sometimes nullable types can be very useful and they can really make coding easier and accurate. Imagine a column in a table that stores a flag and the column accepts null value.

You may in your application declare a nullable of Boolean that stores the value from that column. If the column has a null value, your variable will have a null value as well. You don’t need to assume default values for your variable what may in some cases store fake data.

How to…

1. Declare a nullable type

There are two different syntaxes to declare a nullable type:

Nullable<bool> myNullBoolean;
bool? myNullBoolean;

2. Check if a nullable type has a value

To check if a nullable type has a value, the read-only property HasValue will help you to achieve that.

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

3. Retrieve the nullable type value

To retrieve the value you may use the Value property or one of the GetValueOrDefault method overloads. The Value property should be used in conjunction with the HasValue property to ensure that your code will try to access the value only if there is a value.

myNullBoolean.Value;
myNullBoolean.GetValueOrDefault();
myNullBoolean.GetValueOrDefault(bool);

4. Assign a nullable type to a non-nullable type

When you assign a nullable type to a non-nullable type you need to ensure that a value will be always assigned, forcing you to set a default value with the ?? operator as demonstrated on the following code:

bool myBool = myNullBoolean ?? false;

Advertisements

Responses

  1. The method GetValueOrDefault has an overload with a parameter ‘defaultValue’ of the same type of the object. So in this case we could also do this:

    bool myBoolean = myNullBoolean.GetValueOrDefault(true);

    :)

  2. Cool! I rarely work with nullable types, actually I avoid using them. But those tips are great!

    Also Thiago showed a nice tip.

    Thanks guys.

  3. me checking this tip again… forgot a detail…


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: