Reputation: 5101
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:
Upvotes: 0
Views: 429
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