0

I would like to make the following function work:

    T GetRowVal<T>(System.Data.DataRow dr, string fieldName)
    {
        var type=typeof(T);
        var val = dr[fieldName];
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            if (val == DBNull.Value || val == null) return null;
        return (T)val;
    }

Of course, not having constraints on the T type it doesn't want to return null even if it should be allowed in this case. How can I correct this function? (Or if there is a better way to do it, please let me know).


For know, the approach I would use:

    T GetRowVal<T>(System.Data.DataRow dr, string fieldName)
    {
        var type=typeof(T);
        var val = dr[fieldName];
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            if (val == DBNull.Value || val == null) return default(T);
        return (T)val;
    }

New solution :)

return dr.Field<T>(fieldName);

Not sure it is nicer in terms of performances, but probably looks cleaner.

The implementation can be found on MS Github:

https://github.com/Microsoft/referencesource/blob/master/System.Data.DataSetExtensions/System/Data/DataRowExtensions.cs

Jean
  • 4,911
  • 3
  • 29
  • 50

2 Answers2

1

your only option is return default(T);

TakeMeAsAGuest
  • 957
  • 6
  • 11
0

I found a similar question with what seems to be a good response here:

Nullable type as a generic parameter possible?

Nullable<T> GetRowVal<T>(System.Data.DataRow dr, string fieldName)

as the signature could work.

  • The issue is that it would require a cast after or a call to .Value if the type is not Nullable I guess. – Jean Jun 02 '17 at 20:00