Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic field getter for a DataRow

I try to extend the DataRow object with this generic method :

public static T? Get<T>(this DataRow row, string field) where T : struct
{
  if (row.IsNull(field))
    return default(T);
  else
    return (T)row[field];
}

It's work fine when T is int, decimal, double, etc.

But when I try to use with string, I have this error :

"The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'"

How can I correct this ?

I know that string is not a struct but I wan't to return null if the string field is DBNull.

like image 837
A.Baudouin Avatar asked Dec 02 '22 03:12

A.Baudouin


2 Answers

I think that this is what you want:

public static T? GetValue<T>(this DataRow row, string field) where T : struct
{
    if (row.IsNull(field))
        return new T?();
    else
        return (T?)row[field];
}

public static T GetReference<T>(this DataRow row, string field) where T : class
{
    if (row.IsNull(field))
        return default(T);
    else
        return (T)row[field];
}
like image 156
satnhak Avatar answered Dec 16 '22 15:12

satnhak


string is not a struct, but a class. That is what the error message tells you. Just remove the constraint.

Maybe you want to have a look at the DataRowExtensions.

like image 38
sloth Avatar answered Dec 16 '22 16:12

sloth