ADO.Net and Extension Methods
One of the most tedious things I tend to do is check for nulls on data tables and data sets when I am using them in code. This should be done whenever you receive an object as a result of a function or passed in as a parameter to a function (good coding practices). This can be painful though.
This function is dangerous as the table being passed in could be null so when you try to access the Rows collection a null reference exception occurs.
private static int GetDataTableCount(DataTable table) { int count = table.Rows.Count; return count; }
This next section checks for null and returns zero. It still is tedious and you have to remember to check for null. Again – this should be ingrained in your brain – but the world does have novice programmers out there that don’t do this.
private static int GetDataTableCount(DataTable table) { if (table == null) return 0; int count = table.Rows.Count; return count; }
To get around this I added a class that has extension methods for ado.net objects. The first method checks to see if it has rows. The other gets the row count and returns –1 if the table is null.
public static class AdoExtensions { /// <summary> /// Determine if a data table has rows in it - return false if 0 rows or null /// </summary> /// <param name="table"></param> /// <returns></returns> public static bool HasRows(this DataTable table) { bool hasRows = true; if (table == null || table.Rows.Count == 0) hasRows = false; return hasRows; } /// <summary> /// Get number of rows from table - return number of rows or -1 if table null /// </summary> /// <param name="table"></param> /// <returns></returns> public static int RowCount(this DataTable table) { int rows = -1; if (table != null) { rows = table.Rows.Count; } return rows; } }
The usage using the RowCount Function.
private static int GetDataTableCount(DataTable table) { return table.RowCount(); }
The usage using the HasRows Function
private static int GetDataTableCount(DataTable table) { if(table.HasRows()) { return table.Rows.Count; } else { return -1; } }
This is just one example of how extension methods can make your data processing layer a little more robust with automatic null checking.