God of Source God of Source - 2 months ago 33
C# Question

Generic DataRow extension

I use a extension method to check a DataRowField for null

public static string GetValue(this System.Data.DataRow Row, string Column)
{
if (Row[Column] == DBNull.Value)
{
return null;
}
else
{
return Row[Column].ToString();
}
}


Now I wonder if i could make this more generic. In my case the return type is always string but the Column could also be Int32 or DateTime

Something like

public static T GetValue<T>(this System.Data.DataRow Row, string Column, type Type)

Answer
public T GetValue<T>(this System.Data.DataRow Row, string Column)
{
    return Row.IsNull(Column) ? default(T) : (T)Row[Column];
}

or you can check how the DataRow.Field<T>(columnName) extension does the unboxing here http://referencesource.microsoft.com/System.Data.DataSetExtensions/a.html#ee33bac2abcfb06e

Comments