dotnet / dotnet/csharpstandard

“Defensive” copies – standardising a compiler strategy or language semantics?

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

Description

@KalleOlaviNiemitalo uses the following [code](https://github.com/dotnet/csharpstandard/pull/673#discussion_r1336779227) in a comment on PR #673:

```csharp
struct S {
int P => 0; // not readonly

int this[string s] => 0; // not readonly

readonly void M() {
_ = P; // warning CS8656: Call to non-readonly member 'S.P.get' from a 'readonly' member results in an implicit copy of 'this'.
_ = this[""]; // warning CS8656: Call to non-readonly member 'S.this[string].get' from a 'readonly' member results in an implicit copy of 'this'.
N(); // warning CS8656: Call to non-readonly member 'S.N()' from a 'readonly' member results in an implicit copy of 'this'.
}

void N() {}
}
```

@KalleOlaviNiemitalo is making a point about the warnings Roslyn issues, not about the three copies of `this` the Standard *mandates* as “defensive copies” as being redundant.

Surely a different compiler might choose to analyze `P`, `this[]` & `N`; figure out they do not modify the struct; skip the defensive copies; produce the intended semantics; and yet be non-compliant for doing so…

Are not defensive copies a *compiler strategy* for achieving a particular *semantics*; is the Standard mandating the strategy rather than the semantics; and in doing so limiting compilers (and performance in this case)?

Should not the strategy be left to the compilers, and the semantics to the Standard?

Or is it argued that the strategy here *is* the intended semantics?

[Ducking ;-)] Maybe someone should look into this…

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.