IsDBNull generic shortcut function

question-markHi All,

If you’re working with data from Sql database or from any other database for that matter you probably know the exception cause by calling the reader["columnName"]

This exception is exceptionally annoying because you cannot predict when it is going to happen, it depends on data from the database and can throw the exception at any time.

So, while working on a code that’s not mine, as you know I’m a consultant so I work on other peoples code most of the time.

The way they worked around the issue is like so:

browserTarget = String.Empty;

if (!currReader.IsDBNull(3))
     browserTarget = currReader.GetString(3).Trim();

Now, can you imagine this on every column in the DB which includes 30 columns?

I had to figure out a way to make this generic and just pass it on to the other developers in the company.

scrtch

this is what I wrote for them

And this is how you call the function

public static class DbHelpers
{
	public static objectType convertToGenericObject<objectType>(object readerColumn)
	{
		objectType returnValue;

		if (!Convert.IsDBNull(readerColumn))
			returnValue = (objectType)readerColumn;
		else
			returnValue = default(objectType);
		return returnValue;
     }
}

objectType is the type you want the function to return and the object readerColumn is simply the reader["columnName"] or reader["columnIndex"].

This function won’t throw an exception even if the Db column is null.

Avi Tzurel

My name is Avi Tzurel. I'm a professional web developer from Israel. I spend most of my day developing both web products and RIA applications as well as imparting my experience onto others. I speak, teach and write about my passions, and develop applications according to what I preach. I specialize in Flex, Adobe Air, HTML, XHTML, Javascript, jQuery and other Javascript libraries, on the server side I do .net along side with Ruby on Rails. You can connect with me on Twitter or email me through the contact page on this blog.

Posted Monday, August 31st, 2009 under General, asp.net.

One comment so far

Leave a Reply