Nullable type as a generic parameter possible?
Change the return type to Nullable<T>
, and call the method with the non nullable parameter
static void Main(string[] args)
{
int? i = GetValueOrNull<int>(null, string.Empty);
}
public static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct
{
object columnValue = reader[columnName];
if (!(columnValue is DBNull))
return (T)columnValue;
return null;
}
public static T GetValueOrDefault<T>(this IDataRecord rdr, int index)
{
object val = rdr[index];
if (!(val is DBNull))
return (T)val;
return default(T);
}
Just use it like this:
decimal? Quantity = rdr.GetValueOrDefault<decimal?>(1);
string Unit = rdr.GetValueOrDefault<string>(2);
Just do two things to your original code – remove the where
constraint, and change the last return
from return null
to return default(T)
. This way you can return whatever type you want.
By the way, you can avoid the use of is
by changing your if
statement to if (columnValue != DBNull.Value)
.