Null conditional foreach #4774
-
I'm not really sure what the feasibility of this is, but I feel like C# is missing a directly null-safe foreach that can handle null collections. Boilerplate code like this comes up all the time, usually in one of two forms:
And:
I'm not sure what the best syntax would be, but I'm kind of thinking just:
Which seems to parallel the syntax of the existing null-conditional (and null-coalescing to some extent) operators in that the The effect would be that null collections would be treated like empty collections. It is definitely syntactic sugar, but at the same time so are the null-conditional and null-coalescing operators; and they're very useful. My assumption is that a null-safe Looking at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#the-foreach-statement, it seems like most (all?) of the existing resolution rules can remain as-is. The current equivalent expanded code is stated to be:
For the equivalent null-conditional version, there is a bit of an issue here in that we don't have nullable mutable value types, so e.g. this, while tempting, is a problem (remember
And so the only thing I can think of is to just wrap the entire vanilla version in an One question I have is, is there any chance that
... I think. Maybe. Anyways I'm curious to hear some thoughts on this, in particular:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Beta Was this translation helpful? Give feedback.
#1081