Smoother generics with Nullable<> and NRT #6503
Replies: 5 comments 9 replies
-
This is an accepted aspect of the design of NRTs as they had to be necessarily different from NVTs and that does affect how they work with generics. With NVTs the wrapper struct |
Beta Was this translation helpful? Give feedback.
-
I am Curious - why is Nullable constrained to structs? |
Beta Was this translation helpful? Give feedback.
-
I agree the current solution struggles a bit with generics in particular. I haven't through this through too deeply yet, but would it make sense to have some syntax to refer to the non-nullable version of a generic type? For the sake of the example, say it's just the type parameter followed by an exclamation mark - might have to choose something else if this clashes with existing use cases for null forgivability etc., but anyway. Let's say the compiler does the following:
Then maybe you could have something like
Which I think would enable usage such as:
Similarly (even if the ship might have already sailed for this one), maybe instead of where TKey : notnull, we could have
|
Beta Was this translation helpful? Give feedback.
-
One of the features that is really missing from generics is generic specialization both at the type level and constraint level that part of it is discussed here #6308. |
Beta Was this translation helpful? Give feedback.
-
Having discussed this at length, extending |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
I have used and loved generics for a long time now. But when it comes to NRT, I often get the feeling that the language does not offer the full potential yet. There is a lot of friction between the world of nullable structs and NRT. And IMO, this should be reduced as much as possible.
One example is generic code that should be able to handle "everything nullable":
It is a class that should collect all values that are not null. But how do I use it with a struct?
It just does not work. Or am I overlooking something?
Things get even worse when I use a dictionary inside
CollectNotNull
likeDictionary<T, object>
. Then, I need to add a constraint:where T : notnull
, which does exclude the definition ofc1
already.I am by no means an expert on the way, this could be changed. I am just a user reporting what I feel is a weakness. A weakness that forces me to duplicate code.
The example above is just an artificial example. I met this kind of restriction at different points in the real world.
Beta Was this translation helpful? Give feedback.
All reactions