Welcome to fuzzydev Sign in | Join | Help
in Search

.Net

System.Nullable A.k.a Nullable types

Developers were always looking forward to the inclusion of Nullable types in C#. I love the way it's been implemented using generics. Before we go in to the specifics of Nullable types; let's look at what is a Nullable type and it's usage.

What's a Nullable type?
A nullable type is a value type which can be assigned a null value. Type's like int/bool/double/etc... now can be assigned null values.

Usage:
A simple case for nullable type is while assigning a database column value to a value type.

Example:
int iEmpId = 0;
//Will throw an error if the DataReader value is null
iEmpId = (int)drEmployee["id"];

Now let's see how a value type can be promoted to a Nullable type with the magic of generics.

Declaring a nullable type is straight forward..

System.Nullable<int> iEmpId;
or
int? iEmpId; //that's a shorthand
iEmpId = null; //Allowed as it's Nullable
if(iEmpId.HasValue){
//do something
}

So for assigning a value from let's say a datareader, we could do something like this.

int? iEmpId = null;
iEmpId = (int?)drEmployee["id"];
if(iEmpId.HasValue){
//do something
}

Hmm that certainly makes sense, isn't it?

Published 09 June 2006 by sachinjoshi
Filed Under:
New Comments to this post are disabled

This Blog

Post Calendar

<June 2006>
SuMoTuWeThFrSa
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

Sponsored Links

Syndication

Copyright 2006, Sachin Joshi. All rights reserved.
The content on this site represents my own personal opinions and thoughts at the time of posting, and does not reflect those of my employer's in any way.
Powered by Community Server, by Telligent Systems