Skip to content

Commit

Permalink
Add note about interactions in operators (#18124)
Browse files Browse the repository at this point in the history
* Add note about interactions in operators

Fixes #17988.  See #17988 (comment)

The null conditional operators and null forgiving operators interact in interesting ways. Add notes on both pages to explain those interactions.

* respond to feedback

* typos

* rework note based on feedback.

* one final set of changes
  • Loading branch information
BillWagner authored Apr 29, 2020
2 parents d2a7aa0 + 0ab5420 commit 8c09903
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ In the preceding example, if you don't use the `??` operator, `numbers?.Length <

The null-conditional member access operator `?.` is also known as the Elvis operator.

> [!NOTE]
> In C# 8, the null-conditional operators interacts with the [null-forgiving operator](null-forgiving.md) in an unexpected way. For example, the expression `x?.y!.z` is parsed as `(x?.y)!.z`. Due to this interpretation, `z` is evaluated even if `x` is `null`, which may result in a <xref:System.NullReferenceException>.
### Thread-safe delegate invocation

Use the `?.` operator to check if a delegate is non-null and invoke it in a thread-safe way (for example, when you [raise an event](../../../standard/events/how-to-raise-and-consume-events.md)), as the following code shows:
Expand Down
3 changes: 3 additions & 0 deletions docs/csharp/language-reference/operators/null-forgiving.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ Available in C# 8.0 and later, the unary postfix `!` operator is the null-forgiv

The null-forgiving operator has no effect at run time. It only affects the compiler's static flow analysis by changing the null state of the expression. At run time, expression `x!` evaluates to the result of the underlying expression `x`.

> [!NOTE]
> In C# 8 the null-forgiving operator interacts with the [null-conditional operators](member-access-operators.md#null-conditional-operators--and-) in an unexpected way. The expression `x?.y!.z` is parsed as `(x?.y)!.z`. Due to this interpretation `z` is evaluated even if `x` is `null`, which may result in a <xref:System.NullReferenceException>.
For more information about the nullable reference types feature, see [Nullable reference types](../builtin-types/nullable-reference-types.md).

## Examples
Expand Down

1 comment on commit 8c09903

@springy76
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So it's currently open that|if the behavior might change (in a breaking way) for C# 9 or above?

Please sign in to comment.