Return null from generic method
default(T)
works in both cases.
default(T)
does function in both cases, but its meaning is slightly different for value types. It literally returns the default value of the type. In the case of Method<int>
, it will return 0
, not null
.
UPDATE: Given your method signature:
protected T ValueOrDefault<T>(IDataReader reader, int ordinalId)
You can't return Nullable<T>
in the case of a value type and type T
in the case of a reference type. That would have to be two different methods.
Obviously you can only return null
if the return type is either Nullable<T>
or a reference type. Normal value-types have no null
.
For reference types default(T)
is null
, and for Nullable<T>
it's null too. So you can use default(T)
in both cases where null
exists.
If the type is another value-type default(T)
will not be null
, but since there is no null
that wouldn't make sense anyways.
It is not possible to simply have a method that has return type T
if T
is a reference-type/Nullable<T>
and T?
for normal value types.
One could try to define something like this, but it won't compile because the compiler doesn't understand that the generic constraints are mutually exclusive. It just doesn't consider generic constraints for that.
T? a<T>()
where T:struct
{
}
T a<T>()
where T:class
{
}
You need to make these methods different in some other way. Either by using different names or different parameters.