Generic Extension Methods Example
Ayende has posted about generic extension methods, in particular his surprise that they work at all. In the same vein, I thought I'd post some code that we're using in production here at work.
Pete had to assign a bunch of data to a set of rows in a DataTable, but didn't want to change anything if the values were the same. Rather than writing lines and lines of comparisons and assignments, we made ourselves an extension method on DataRow that only overwrites the field's value if it's DbNull or different to the value we've given it.
As a bonus, these extension methods support nullable types, so if you pass in a Nullable<int> then we can test for null and assign DbNull to the field. Also note there's a special one at the top just for string, since we want to trim the string before comparing (in the case of plain old char fields).
public static void SmartAssign(this DataRow row, string columnName, string value)
{
if (row == null) throw new ArgumentNullException("row");
int columnIndex = row.Table.Columns.IndexOf(columnName);
if (value == null)
{
row[columnIndex] = DBNull.Value;
return;
}
value = value.Trim();
if (row.IsNull(columnIndex))
{
row[columnIndex] = value;
return;
}
string currentValue = row[columnIndex].ToString().Trim();
if (value != currentValue)
{
row[columnIndex] = value;
}
}
public static void SmartAssign<T>(this DataRow row,
string columnName, T value)
{
if (row == null) throw new ArgumentNullException("row");
int columnIndex = row.Table.Columns.IndexOf(columnName);
if (value == null)
{
row[columnIndex] = DBNull.Value;
return;
}
if (row.IsNull(columnIndex))
{
row[columnIndex] = value;
return;
}
if (!value.Equals(row[columnIndex]))
{
row[columnIndex] = value;
}
}
public static void SmartAssign<T>(this DataRow row,
string columnName, Nullable<T> value) where T : struct
{
if (row == null) throw new ArgumentNullException("row");
int columnIndex = row.Table.Columns.IndexOf(columnName);
if (!value.HasValue)
{
row[columnIndex] = DBNull.Value;
return;
}
if (row.IsNull(columnIndex))
{
row[columnIndex] = value.Value;
return;
}
if (!value.Equals(row[columnIndex]))
{
row[columnIndex] = value.Value;
}
}
# Trackback from Jason Haley on 27/02/2008 12:57 AM