I have a database with a nullable column foo_date, where Npgsql maps the sql NULL value to an instance of the C# class DBNull. In my C# aggregate I use the type DateTime? for said column. So the question is how to easily convert DBNull to a nullable type.
I want to write a utility method like, e.g.,
public static class DbUtil
{
public static T? CastToNullable<T>(object obj)
{
if (DBNull.Value.Equals(obj))
return null;
return (T)obj;
}
}
which I would like to use like this:
IDataRecord rec = ...
DateTime? fooDate = DbUtil.CastToNullable<DateTime>(rec["foo_date"]);
However, I get the compiler error:
Error CS0403 Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead.
When I replace return null by return default(T?), the compiler is happy, but the method does not return null but the default Date, i.e., 01.01.0001.
What is the correct way to write the generic utility method above?