I want to do something like this :
myYear = record.GetValueOrNull<int?>("myYear"),
Notice the nullable type as the generic paramater.
Since the GetValueOrNull function could return null my first attempt was this :
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName) where T : class
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
{
return (T)columnValue;
}
return null;
}
But the error I get now is
The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method
Right! Nullable is a stuct! So I tried changing the class contstrainted to a stuct constrained (and as a side effect can't return null anymore) :
public static T GetValueOrNull<T>(this DbDataRecord reader, string columnName) where T : stuct
Now the assingment
myYear = record.GetValueOrNull("myYear")
Gives the following error
The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
Is specifying a nullable type as a generic parameter at all possible?