DBNull string field handling

Let’s say for the sake of argument that you are using a SQL Server Compact database in your C# .NET application, and your User table has nvarchar fields that are nullable, and your User class doesn’t care if those fields are null, it just wants empty strings instead.

Sadly to say, you are eventually going to end up with nulls in those fields, and as a result, if you use a SqlCeDataReader to step through a record set, this kind of stuff will (at some point) give you a runtime error:

myUser.UserName = (string)dataReader["UserName"]);

So I started looking for the best way to handle this problem. What I didn’t want to do was this for every single string field assignment:

myUser.UserName = (System.DBNull.Value == dataReader["UserName"] ? "" : dataReader["UserName"]);

This seems a bit wasteful to me, as the data reader is accessed twice. Sure, I could have encapsulated this into a function to pretty up the code a bit, but that would just be hiding the ugliness. Then, it occurred to me to try the Convert class to see what would happen, and it turns out that this code knows how to convert a DBNull to an empty string:

myUser.UserName = Convert.ToString(dataReader["UserName"]);

The Convert class may in fact do the same thing as I have shown above, but I would hope that Microsoft would make their built in function better than something that I would just hack together.

BTW, I hope everyone out there has voted, this is an important election. (Finally, tomorrow I can watch TV or get the mail without being bombarded by increasingly stupider campaign and “issue” advertisements.)

Leave a Reply