IsDBNull generic shortcut function


If you’re working with data from an 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:

csharp browserTarget = String.Empty;

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

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.


This is what I wrote for them

and this is how you call the function

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

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

} /csharp


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

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at