C# - 13 - More fun with nulls.

[C# 2.0]

When pulling data out of a DataReader, do you ever write code that looks like this?

Unfortunatly you can't use the null coalessor (as described in a previous tip) becasue DBNull.Value isn't the same as null.

Try adding the following module to your project:

The FromDB method will convert DBNull.Value into null. The ToDB method does the opposite. Now you can rewrite your original code like this:

At first glance that might not look much better. But consider, the field name is only entered once, instead of twice, and this makes it less error prone.

(Note the use of a nullable int? and a null coalessor on the third line. This is because the ColourName method previously written expects a non-null int.)


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License