csharpstandard icon indicating copy to clipboard operation
csharpstandard copied to clipboard

Add support for readonly members in structs

Open RexJaeschke opened this issue 3 years ago • 4 comments

RexJaeschke avatar Nov 27 '22 16:11 RexJaeschke

This will also need to update the defensive copying rule like in https://github.com/dotnet/csharpstandard/issues/894.

Tracked as https://github.com/dotnet/csharpstandard/issues/928

KalleOlaviNiemitalo avatar Aug 16 '23 11:08 KalleOlaviNiemitalo

rebased on 09/26/2023, various links also fixed.

BillWagner avatar Sep 26 '23 14:09 BillWagner

Overall it feels like we may be missing a brief section explaining the purpose of readonly members on structs.

I'd also expect there to be a change somewhere to what happens when member access via a readonly field (in either a class or a struct) invokes a readonly member... shouldn't we be removing a defensive copying step there? Apologies if I've missed it... I look forward to it being pointed out :)

See #1053

Nigel-Ecma avatar Mar 04 '24 01:03 Nigel-Ecma

It’s the next day and I’m commenting on my own introductory comment on my review as an important issue probably doesn't come across clearly in the review itself:

I think we need to pull out bits into a common ”readonly members” section so we have a single place to define what being a read-only member means.

Unless I'm missing something the Standard is missing a clear explanation of semantics of read-only members, and those semantics some might find “surprising”.

It is reasonable to assume that a read-only member reports on the current state of an object and does not modify it. C# does the latter but not necessarily the former...

If a read-only member attempts to modify the state a reasonable assumption is that an error would be produced, the member is read-only after all.

C# chooses a different approach: it makes a copy of the object, mutates the state of that copy, and then discards the copy. The C# choice could be “surprising”, something Roslyn seems to acknowledge by issuing a warning, but I don’t think the Standard is clear as it could be on the semantics as it is preoccupied with the “how” a compiler might achieve this result, the so called “defensive copies”.

Such an description doesn’t need to be long and complicated, it doesn’t need to justify C#’s choice, it just needs to be clear.

Refs: https://github.com/dotnet/csharpstandard/pull/673#discussion_r1510548259 & #1053

Nigel-Ecma avatar Mar 04 '24 17:03 Nigel-Ecma