A similar question, but without casting the T parameter.
This does not work
public T GetValueG<T>(string Query)
{
object value = DBNull.Value; // Read from Database which can return DBNull
if (value is DBNull)
return (T)null;
else
return (T)value;
}
Error CS0037 Cannot convert null to 'T' because it is a non-nullable value type
But this works
public T GetValueG<T>(string Query)
{
object value = DBNull.Value; // Read from Database which can return DBNull
if (value is DBNull)
value = null;
return (T)value;
}
I know that using constraint type where T: struct
will make T to be able to be cast with null directly.
But in the second approach, why does it accept an object which is 100% can be null? Why can't I return null directly without an object or something either?