IsDBNull generic shortcut function
Hey all,
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;
if (!Convert.IsDBNull(readerColumn))
returnValue = (objectType)readerColumn;
else
returnValue = default(objectType);
return returnValue;
}
}
[/csharp]
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.