Tuesday, January 22, 2008
« Yet Another Interview Question | Main | #1 Faster Coding »

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)) { }

{6230289B-5BEE-409e-932A-2F01FA407A92}

 

C# | Wayne
Thursday, January 10, 2008 4:22:05 PM (Pacific Standard Time, UTC-08:00)
What about Boolean.TryParse()? That way you could do it without a nullable type (if that is an option). The following should work.


#region private fields

bool _isValid = false;


#endregion private fields

IsValid = Boolean.TryParse(reader["IsValid"], out _isValid);

Another option (probably not a best practice but would work):

public static List<Foo> RetrieveDataFromSql(Foo foo)
{
List<SqlParameter> parameters = Database.CreateParameters(foo);
return Database.GetTable<Foo>(parameters, "sproc").FindAll(delegate (Foo foo) { return foo.IsValid != null && foo.IsValid; });
}

This way you have a List<T> of only true objects (or true / false if you alter the predicate).

I use this approach if wanting to display data to certain account types. For example, a manager might want all the historical data returned while the employee should only view data from today outwards. That's been a requirement in the past and all I do is pass in a bool "isManager" or something similar.

List<T> list = Database.GetTable<T>(parameters, "sproc");
return isManager ? list : list.FindAll(delegate (T t) { return t.DateTimeField.Date >= DateTime.Today.Date; });

To get back on-topic, if I can help it I filter by NOT NULL in a view somewhere (or table by way of stored procedure). I usually don't even display this field as output, simply a WHERE clause.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview