Wednesday, January 23, 2008

When Is null not true?

In C# we can have nullable types, like this:

Boolean? isValid;

Which means that isValid can be true, null, or false.  It is like a three way switch.  I use it to represent a bit field in SQL Server that can have a null value.  For example I might have this table:

CREATE TABLE Account (IsValid bit)

Which creates me a table with a bit column that can be NULL.  I usually don't like to do this -- in fact I never do, however I am working with some people that don't bother to check the NOT NULL when they use the designer so I have to deal with it in my C# code.  So I ask the table designer what NULL means in the IsValid coulmn and he tells me it means false (not valid).

So I query the database and set the result to isValid, in the C# class above.  So now I need to check to see if the account is valid.  It might seem like this would work:

if (isValid) {...}

However, that throws a compiler error, becuase you can't have Nullable type default expression.  So I have to do this:

if (isValid == true) { }

Notice that the second statement is really saying that the expresion fails if the IsValid is false or null.  This is also the same but weak:

If ((isValid!=null) && (((Boolean)isValid)==true)) { }



No comments:

Post a Comment