IsDBNull generic shortcut function

tweet! tweet this post subscribe! subscribe to RSS feed
question-mark

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.

scrtch

This is what I wrote for them

and this is how you call the function

csharp 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;
 }

} /csharp

objectType

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

  • Tags:
tweet! tweet this post subscribe! subscribe to RSS feed

This theme was created by: Jeff Kreeftmeijer, Thank you!

 
Fork me on GitHub