I was wondering why this was the case, as it went against what I would have expected. This has to do with how Generic Nullable types are interpreted in C#.
public static int? MyFunction(){
return default;
}
public static T MyFunctionGeneric<T>() {
return default;
}
public static T? MyFunctionGenericNullable<T>(){
return default;
}
public static void main(string[] args){
Console.WriteLine(MyFunction());
Console.WriteLine(MyFunctionGeneric<int?>());
Console.WriteLine(MyFunctionGenericNullable<int>());
}
As expected, when I define the return type as int? the default returned value is null.
This is also the case when I define a generic that returns its own type, because int? is passed in, the default returned value is null.
However, in the third case, even though the return type is technically int?, the default returned value is 0. I would have to pass in int? as my type parameter to get a null response. Note that this happens even when I explicitly state return default(T?)
This is a little bit unexpected, does anyone have an explanation for it?
staticso that people can just cut and paste this code into a console app to reproduce it.