Wednesday, 18 July 2007

C# As, Is and Cast

One of the lovely problems you always get when dealing with databases is DBNulls popping up and ruining conversions to strings, datetimes etc.

Use of "as" and "is" will sort this out.

If you are casting a reference type use "as":

string bob = dr["bob"] as string;

If using a value type use "is" first

DateTime currentTime = DateTime.MinValue;
if (dr["currentTime"] is DateTime)
currentTime = (DateTime)dr["currentTime"];

This means that you shouldn't end up with DBNull casting errors.

No comments: