Proposal: syntax for null-propagating arguments in method calls #433
Replies: 7 comments
-
See: dotnet/roslyn#5961 |
Beta Was this translation helpful? Give feedback.
-
Thanks, I hadn't seen that. That proposal is much more comprehensive and consistent, at the cost of taking on extra ontological baggage (poison values, etc.), which seems hard to justify because null propagation is inherently kind of hacky. This is meant to cover what I'll vainly guess are a strong majority of null propagation use cases, but stay in the spirit of I also think the prefix |
Beta Was this translation helpful? Give feedback.
-
My opinion is that the primary issues identified in that Roslyn proposal are the same as exist here in that it is some operator applied to an argument expression that alters the behavior of the parent expression, even if that is just limited to a method call. |
Beta Was this translation helpful? Give feedback.
-
Using #176 you could do: object M() {
return SomeMethod(a ?? return null, b, c ?? return null, ...)
} You can already do |
Beta Was this translation helpful? Give feedback.
-
Maybe we could have |
Beta Was this translation helpful? Give feedback.
-
I don't think that's a good idea. Returning from a method is too big of a side-effect to be hidden inside just two fairly inconspicuous characters. |
Beta Was this translation helpful? Give feedback.
-
I agree. just for reference, Rust's |
Beta Was this translation helpful? Give feedback.
-
Before C# 6, I've often been tempted to add an
IfNotNull<T>(this object x, Func<object, T> f)
or similarextension method for short-circuiting null-propagating execution. I'd expected that C# 6's
?.
operatorwould "solve the problem" and remove this temptation, but what I've found in practice is that it's more
common to want to pass a maybe-null object into a method that doesn't accept null arguments, rather than accessing a member on a maybe-null object.
An approach I think could nicely complement
?.
for this case would be to extend method call syntax toallow each argument to be marked as null-propagating:
SomeMethod(?a, b, ?c, ...)
which would return null if any of the arguments prefixed with
?
are null, and evaluate as usual otherwise. (so returnsT?
if the return typeT
is a value type.)(unsure about: should the first null
?arg
encountered short-circuit evaluation of subsequent arguments?)I like this syntax because of the feeling of symmetry or duality with
?.
- inobj?.Member
, the required data flows from left to right, and the?
is like a guard that intercepts null values before they can reach the.
, and changes the evaluation of the overall expression. InMethod(?arg)
, the data flows from right to left, and the?
intercepts the null value before it reaches the(
, and changes the overall evaluation. So by covering both cases or directions, I think the null-propagation functionality overall would feel more cohesive and less surprising.Beta Was this translation helpful? Give feedback.
All reactions