Merge pull request #1721 from 333fred/null-coalescing-updates
Update null-coalescing-assignment proposal with changes from LDM.
This commit is contained in:
commit
f4f9f590da
1 changed files with 19 additions and 2 deletions
|
@ -10,6 +10,8 @@
|
|||
|
||||
Simplifies a common coding pattern where a variable is assigned a value if it is null.
|
||||
|
||||
As part of this proposal, we will also loosen the type requirements on `??` to allow an expression whose type is an unconstrained type parameter to be used on the left-hand side.
|
||||
|
||||
## Motivation
|
||||
[motivation]: #motivation
|
||||
|
||||
|
@ -37,7 +39,22 @@ assignment_operator
|
|||
;
|
||||
```
|
||||
|
||||
Which follows the [existing semantic rules for compound assignment operators](https://github.com/dotnet/csharplang/blob/master/spec/expressions.md#compound-assignment). What that means is that an operation of the form `x ??= y` is processed as if written `x = (x ?? y)` (except `x` shall be computed once). However, we permit the assignment to `x` (of its existing value) to be elided in the case that `x` is not null.
|
||||
Which follows the [existing semantic rules for compound assignment operators](https://github.com/dotnet/csharplang/blob/master/spec/expressions.md#compound-assignment), except that we elide the assignment if the left-hand side is non-null. The rules for this feature are as follows.
|
||||
|
||||
Given `a ??= b`, where `A` is the type of `a`, `B` is the type of `b`:
|
||||
|
||||
1. If `A` does not exist or is a non-nullable value type, a compile-time error occurs.
|
||||
2. If `B` is not implicitly convertible to `A`, a compile-time error occurs.
|
||||
3. The type of `a ??= b` is `A`.
|
||||
4. `a ??= b` is evaluated at runtime as `a ?? (a = b)`, except that `a` is only evaluated once.
|
||||
|
||||
For the relaxation of the type requirements of `??`, we update the spec where it currently states that, given `a ?? b`, where `A` is the type of `a`:
|
||||
|
||||
> 1. If A exists and is not a nullable type or a reference type, a compile-time error occurs.
|
||||
|
||||
We relax this requirement to:
|
||||
|
||||
1. If A exists and is a non-nullable value type, a compile-time error occurs.
|
||||
|
||||
## Drawbacks
|
||||
[drawbacks]: #drawbacks
|
||||
|
@ -47,7 +64,7 @@ As with any language feature, we must question whether the additional complexity
|
|||
## Alternatives
|
||||
[alternatives]: #alternatives
|
||||
|
||||
The programmer can write `(x = x ?? y)` or `if (x == null) x = y;` by hand.
|
||||
The programmer can write `(x = x ?? y)`, `if (x == null) x = y;`, or `x ?? (x = y)` by hand.
|
||||
|
||||
## Unresolved questions
|
||||
[unresolved]: #unresolved-questions
|
||||
|
|
Loading…
Reference in a new issue