Nullable value types

I’ve been playing around with c# 2.0 for awhile now. 
As a side project, and to give me something to implement in Visual C# Express, I
was planning on rewriting the o/r mapper/data access objects that we use at
work.  At first I was really excited to use generics to
greatly simplify our database collection classes, and so far the generics have
been great, I’ve reduced much of the code, and I don’t have to use nearly as
many boxing operations.

An annoying thing about mapping database values to language
values, is that fields in the database can be null, whereas in c#, a null value
would make no sense.  An int for example, you never say “int n = null;”,
but you can certainly have a null value in the database for an int field. 
So while I was happy to use generics, I was just as excited to learn that in c#
2.0, MS has implemented nullable value types. What that means is that you now
CAN write something like “int n = null;”, however the syntax is actually “int? n
= null;”.  The way that nullable types work is actually based on generics :-) .  There is a new struct in c# called Nullable<T> where T is the
type of the value that you want to store.  The syntax I wrote previously is
simply syntactic sugar for this struct. Eric Gunnerson has a good post
about nullable types, and he ought to know, he is a former member of the c# team
at Microsoft.

Some people may not like this as a solution to the database
mapping problem, but I definitely like it, because now, rather than having to
define some default value to set in case of a null database value, I can simply
set the int to null.  I like this approach better because it lets you know
exactly what was in the database. It will cause some more null
checking elsewhere in the application, but I think its worth the extra
effort.

2 Comments

  1. Anonymous said,

    Wrote on May 24, 2005 @ 7:17 pm

  2. philluminati said,

    Wrote on April 1, 2008 @ 11:08 am

    I’ve just been searching the internet for help for this problem so I want to thank you for pointing out.

    now I just do UInt32? value = null;

    I find it ridiculous however that C# is an object-oriented language with automatic boxing and un-boxing and yet I’ve written the whole page before I realised a UInt32 is light shade of green because it’s a struct when I’d previously assumed it was an object.

Comment RSS