I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this:
DataRow row = ds.Tables[0].Rows[0]; string value = (string)row;
What is the best way to deal with DBNull's in this type of situation.
Nullable types are good, but only for types that are not nullable to begin with.
To make a type ‘nullable’ append a question mark to the type, for example:
I would also recommend using the ‘
as‘ keyword instead of casting. You can only use the ‘as’ keyword on nullable types, so make sure you’re casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this isas‘ keyword returnsnullif a value isDBNull.as, but coupled with the reason above it’s useful.I’d recommend doing something like this
In the case above, if
rowcomes back asDBNull, thenvaluewill becomenullinstead of throwing an exception. Be aware that if your DB query changes the columns/types being returned, usingaswill cause your code to silently fail and make values simplenullinstead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.