csharplang/proposals/null-conditional-await.md

56 lines
1.8 KiB
Markdown
Raw Normal View History

2017-02-09 18:02:29 +01:00
# null-conditional await
* [x] Proposed
* [ ] Prototype: None
* [ ] Implementation: None
* [ ] Specification: Started, below
## Summary
[summary]: #summary
2018-10-09 12:04:31 +02:00
Support an expression of the form `await? e`, which awaits `e` if it is non-null, otherwise it results in `null`.
2017-02-09 18:02:29 +01:00
## Motivation
[motivation]: #motivation
This is a common coding pattern, and this feature would have nice synergy with the existing null-propagating and null-coalescing operators.
## Detailed design
[design]: #detailed-design
We add a new form of the *await_expression*:
2019-03-07 19:00:39 +01:00
```antlr
2017-02-09 18:02:29 +01:00
await_expression
: 'await' '?' unary_expression
;
```
The null-conditional `await` operator awaits its operand only if that operand is non-null. Otherwise the result of applying the operator is null.
The type of the result is computed using the [rules for the null-conditional operator](https://github.com/dotnet/csharplang/blob/master/spec/expressions.md#null-conditional-operator).
2017-03-15 20:25:12 +01:00
> **NOTE:**
> If `e` is of type `Task`, then `await? e;` would do nothing if `e` is `null`, and await `e` if it is not `null`.
2019-03-07 19:00:39 +01:00
>
2017-03-15 20:25:12 +01:00
> If `e` is of type `Task<K>` where `K` is a value type, then `await? e` would yield a value of type `K?`.
2017-02-09 18:02:29 +01:00
## Drawbacks
[drawbacks]: #drawbacks
As with any language feature, we must question whether the additional complexity to the language is repaid in the additional clarity offered to the body of C# programs that would benefit from the feature.
## Alternatives
[alternatives]: #alternatives
Although it requires some boilerplate code, uses of this operator can often be replaced by an expression something like `(e == null) ? null : await e` or a statement like `if (e != null) await e`.
## Unresolved questions
[unresolved]: #unresolved-questions
- [ ] Requires LDM review
## Design meetings
None.