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.
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];
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With