Assigning null to T? if typeparameter T is unconstrained #5911
-
Excuse me if this has already been asked before, i searched through the discussions & issues and didn't find this question. I've been working with generics paired with nullability and one pitfall i've ran into again and again is the following: T? ReturnVal<T>() where T : class => null; T? ReturnVal<T>() where T : struct => null; While this one produces an error, claiming "Cannot convert null to type parameter 'T' because it could be a non-nullable value type" T? ReturnVal<T>() => null; Now we are obviously trying to return Reading through the spec, it seems that As far as i can tell, this causes T? in our case to be implicitly converted to T . Additionally, this causes substituting null with default(T?) to return default(T) instead of null , meaning the method will not return null values when called with a struct as type parameter.
Now my question, at the risk of sounding a bit stupid, is: Why? As far as i can tell, there isn't really any type i could pass as a type parameter that could not be made nullable, so why impose this restriction? Is this due to internal limits since struct-null-values are actually the default of Nullable, not genuine null-pointers? Genuinely curious what could be the cause of this, thanks in advance :) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 35 replies
-
@PaulRitter the problem is that not the JITTer implements nullability - it is done by the IL Compiler. For example: static Nullable<T> ReturnVal<T>() where T : struct
{
return null;
} while static T ReturnVal<T>() where T : class
{
return null;
} |
Beta Was this translation helpful? Give feedback.
-
Please look at this: #4080 |
Beta Was this translation helpful? Give feedback.
@PaulRitter the problem is that not the JITTer implements nullability - it is done by the IL Compiler.
For example:
T? ReturnVal<T>() where T : struct => null;
is compiled to:
while
T? ReturnVal<T>() where T : class => null;
is compiled to: