T? with constraint T : class? #2418
Replies: 3 comments
-
if you are saying |
Beta Was this translation helpful? Give feedback.
-
FirstOrDefault is an example of a method which would have such a signature. I think the plan is to use attributes to sort out cases like this. |
Beta Was this translation helpful? Give feedback.
-
I'm not clear on how the proposed attributes are supposed to solve this. It was my understanding that they were for annotating that a method like TryGet would return true iff the out parameter is non-null. But that doesn't help the example above... Changing the constraint on This is important when, e.g., calling a generic method from another generic method.
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
It seems that this constraint is disallowed. But that doesn't seem right. Consider the example:
A<string>.F1
cannot return nullA<string>.F2
can return nullA<string?>.F1
can return nullA<string?>.F2
can return nullA's contract basically says, "I can deal with null T's if you want. F1 will only return null if we're dealing with null T's, but F2 may return a null even if we're not dealing with null T's, e.g. it can be a lookup that can fail."
But this seems to be an error for F2:
error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type. Consider adding a 'class', 'struct', or type constraint.
https://sharplab.io/#v2:EYLgtghgzgLgpgJwDQxASwDZICYgNQA+AAgAwAERAjANwCwAUAwMQB2ArhhhMBnGXC268GRAExkAggB4AKgD4yAdwAWiPjLIgKogPxIyLOIoAUASgYBvBmRsaAYpTNkAvAsOKyMs3Xo3POsjtRJ1cDDgwfAF8GBiA===
Beta Was this translation helpful? Give feedback.
All reactions