Jean
Jean

Reputation: 5101

How to cast a datarow field to a generic type?

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

Upvotes: 0

Views: 429

Answers (2)

user4175265
user4175265

Reputation:

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.

Upvotes: 0

TakeMeAsAGuest
TakeMeAsAGuest

Reputation: 995

your only option is return default(T);

Upvotes: 1

Related Questions