Missing generic constraint for nullable types #2840
Replies: 4 comments
-
From @scalablecory on Thursday, September 26, 2019 6:21:56 PM Why do you need it to be a constraint? Can you put it on the return type? public class Example
{
public T? GetSomething<T>() where T : class
{
return null;
}
} |
Beta Was this translation helpful? Give feedback.
-
From @TobiasvdVen on Friday, September 27, 2019 7:17:44 AM
Interestingly, we thought we had tried that, but apparently only with the class? constraint (not class), which seems to cause a compiler error. This does work for most of our purposes. We do also have a case where we wish the generic function to accept both nullable structs and nullable reference types. Based on this page under The issue with T? heading, however, it seems that this is not possible pragmatically due to underlying differences between int? types and reference types marked as nullable. If that is truly the case, then this issue can probably be closed and we will have to find a different method of achieving the same result as our current implementation. |
Beta Was this translation helpful? Give feedback.
-
There's an attribute for this.
Isn't that what happens by default? SharpLab. Or do you mean that given a |
Beta Was this translation helpful? Give feedback.
-
I've found several cases where I wanted to use |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
From @TobiasvdVen on Thursday, September 26, 2019 9:06:11 AM
During our migration to .NET Core 3.0 we encountered a problem involving generic functions that might return null. See a minimal example below which generates the following warning:
A null literal introduces a null value when 'T' is a non-nullable reference type. (CS8654)
This page lists a generic constraint notnull, but not an equivalent for the opposite.
This page mentions a generic constraint class?. However, the documentation states that this denotes "possibly nullable reference type". Thus, a warning is generated when attempting to return null, as non-nullable reference types are still allowed by the constraint.
Is there a constraint that we have missed which enforces a generic parameter to be nullable, or will this be added in the future?
EDIT:
We found this page which describes The issue with T?. Is there a recommended method to implement a generic method that needs to be able to return null without being able to fully constrain this?
Copied from original issue: dotnet/core#3476
Beta Was this translation helpful? Give feedback.
All reactions