dotnet / dotnet/csharpstandard

Unclear what is the (ref) safe context of an assignment expression

Open
#1,444 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
815
Forks
99
Avg merge
1d 14h
Merged PRs (30d)
16

Description

The standard has [this section](https://github.com/dotnet/csharpstandard/blob/64260655f9d21e0602d5309c0aeeed01d8ed15a1/standard/structs.md#164155-operators), but it is not clear to me from that what is the safe context of an assignment expression (is it its LHS, RHS, combination of both?):

> #### 16.4.15.5 Operators

> The application of a user-defined operator is treated as a method invocation ([§16.4.15.6](structs.md#164156-method-and-property-invocation)).

> For an operator that yields a value, such as `e1 + e2` or `c ? e1 : e2`, the safe-context of the result is the narrowest context among the safe-contexts of the operands of the operator. As a consequence, for a unary operator that yields a value, such as `+e`, the safe-context of the result is the safe-context of the operand.

> > *Note*: The first operand of a conditional operator is a `bool`, so its safe-context is caller-context. It follows that the resulting safe-context is the narrowest safe-context of the second and third operand. *end note*

There is also [a similar section](https://github.com/dotnet/csharpstandard/blob/64260655f9d21e0602d5309c0aeeed01d8ed15a1/standard/variables.md#9725-operators) for ref safe context:

> #### 9.7.2.5 Operators

> The conditional operator ([§12.19](expressions.md#1219-conditional-operator)), `c ? ref e1 : ref e2`, and reference assignment operator, `= ref e` ([§12.22.1](expressions.md#12221-general)) have reference variables as operands and yield a reference variable. For those operators, the ref-safe-context of the result is the narrowest context among the ref-safe-contexts of all `ref` operands.

The standard sections seem to come from [the proposal](https://github.com/dotnet/csharplang/blob/d8d76d718e395cd09b20521233ed6015bc0a4c0d/proposals/csharp-7.2/span-safety.md#operators-including-), but that doesn't provide additional clarity.

I think the safe context of an assignment should be its RHS because that's the result of the assignment expression. Same for ref assignment. Not for null-coalescing assignment though (there it's probably clear already from the spec that it should be the combination of LHS and RHS).

Related change in Roslyn: https://github.com/dotnet/roslyn/pull/80633

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.