Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method return using generics

Is it possible to return a generic type using extension methods?

For example, I have the following method:

// Convenience method to obtain a field within a row (as a double type) 
public static double GetDouble(this DataRow row, string field) {
    if (row != null && row.Table.Columns.Contains(field))
    {
        object value = row[field];
        if (value != null && value != DBNull.Value)
            return Convert.ToDouble(value);
    }
    return 0;
}

This is currently used as follows:

double value = row.GetDouble("tangible-equity");

but I would like to use the following code:

double value = row.Get<double>("tangible-equity");

Is this possible and if so, what would the method look like?

like image 597
Steven de Salas Avatar asked Jan 09 '11 02:01

Steven de Salas


1 Answers

How about this one:

    public static T Get<T>(this DataRow row, string field) where T: IConvertible 
    {
        if (row != null && row.Table.Columns.Contains(field))
        {
            object value = row[field];
            if (value != null && value != DBNull.Value)
                return (T)Convert.ChangeType(value, typeof(T));
        }
        return default(T);
    }

Convert.ChangeType is much more flexible handling conversions as opposed to just casting. This pretty much reflects your original code, just generic.

like image 200
BrokenGlass Avatar answered Oct 13 '22 01:10

BrokenGlass