Jonas Stawski

Everything .NET and More

Nullable Types ?!?!?!?!?!??!?!?!

Today I learned something new. Today I learned this new feature of .net 2.0 and that feature is Nullable Types. What are they? Basically they are a typed object of a primitive/value type that can hold a value or null/nothing.

What's the difference between those types and the primitive ones? The only difference from a usefullness perspective is that you can have primitive values with null rather than a predefined value. Do I think they are usefull? nope, I don't. Do I think they are going to continue on till death do us apart? No, I don't.

What's the difference of setting an integer to a predifined "null" value like -1 rather than null? None, whatsover. The only time I see when it will be usefull is if the integer type can be any of the values from integer.min to integer.max. In that case there is no real value to set as a predefined "null". Is that scenario possible? Yes, it is. Is that scenario a normal ocurrence? Not in my experience.

This thing gets more interesting. What is a boolean? A boolean is a primitive type that can only hold 2 values: True or False. So what is a Nullable Boolean? In simple terms: an oxymoron. If by definition a boolean can have 2 values: true or false, so how can a boolean be null? It can't, because if it is null then it's not a boolean. So what is the conclusion to this? Microsoft used the wrong term for the booleans. Did you ever wonder why SQL Server (just to mention one DB) doesn't have a boolean type? What, MSSQL doesn't have a boolean type?!?!?!?!??!!?!? Nope, it doesn't. It has types that can represent a boolean, but they are not booleans. What are those types? Well any type that can hold at least 2 values: int, bit, varchar(1), char(1), etc, etc. The one that resembles more to the boolean is the bit with 2 possible values: 0, 1; but as any other field in the db, it can contain nulls and therefore it makes it 3 possible values.

Will I ever use this nullable types? probably not, but the nullable int might come in handy.

Too much talk, too little code, so here's how to use nullable types in C# and VB.net:

int? x = null;
bool? flag = null; //Oxymoron :)
//Or
System.Nullable<int> x = null;
System.Nullable<bool> flag = null;

Dim X as Nullable(Of Integer)
Dim flag as Nullable(Of Boolean)

As always, happy programming!!

Comments (1) -

what is the O/P?

Reply

Add comment

biuquote
Loading