roslyn: C#: The compiler should be consistent about issuing error CS1612 when modifying readonly rvalue struct
Version Used: VS 16.6.2
Abstract The C# compiler appears to be inconsistent about issuing CS1612 Cannot modify the return value of ‘expression’ because it is not a variable.
When the value being modified is a readonly struct, the compiler allows the “mutation” (apparently, on the basis that it cannot occur anyway, because the struct is readonly), but only if the struct was returned from a function.
If the struct was returned from a property getter, the compiler issues CS1612, even though the getter-returned value is no more of an rvalue than a function-returned value.
Steps to Reproduce: Have the following code:
static void Main()
{
var f = new S1Factory();
// "Mutating" an rvalue struct returned from a function.
// The compiler allows that, because no mutation can actually occur
// due to the struct being readonly, so no reason to raise error CS1612.
f.GetNewS1AsFunction().CausesSideEffectsWhenWrittenTo = 42;
// Same, but this time the struct is returned from a property getter.
// It is just as much of a readonly rvalue as above, but this time the compiler
// raises CS1612. It shouldn't. Or, it should raise it for the above too.
f.GetNewS1AsProperty.CausesSideEffectsWhenWrittenTo = 42;
}
readonly struct S1
{
// Write-only property. Because the struct is readonly,
// the property only exists for its side effects
public readonly int CausesSideEffectsWhenWrittenTo {
set {
// Cause side effects. The struct cannot be mutated though
// because it's readonly.
}
}
}
readonly struct S1Factory
{
public readonly S1 GetNewS1AsProperty => new S1();
public readonly S1 GetNewS1AsFunction() => new S1();
}
Expected Behavior:
Both assignment lines in the Main() compile.
Or, both don’t compile - I am honestly not sure which one is correct.
Actual Behavior:
The line with f.GetNewS1AsFunction() compiles, the line with f.GetNewS1AsProperty does not, which is inconsistent and confusing.
Note that if you remove the readonly modifier from struct S1 and property CausesSideEffectsWhenWrittenTo, then the compiler will correctly issue CS1612 on both assignment lines, because now that the struct is no more readonly, a call to the write-only property is allowed to mutate the struct, and because it’s an rvalue, the error is correctly raised.
Original StackOverflow question: https://stackoverflow.com/q/62444352/
About this issue
- Original URL
- State: open
- Created 6 years ago
- Reactions: 11
- Comments: 50 (34 by maintainers)
This depends on what the purpose of the
readonlymodifier on types is. As it stands, there are multiple purposes which aren’t fully aligned, the result of which is friction here.Purposes 2 and 3 are both derived from the core functional specification, but they come at odds here, otherwise I would be okay to remove
readonlymodifier from my struct.Regarding purpose 2, the convention:
structtypes will check the definition to see thereadonlymodifier.refit has no effect or restriction on the behaviour of user code (outside of this warning). It can only be used to help reason about the underlying implementation of the type. Personally, I like to know the implementation of my types, not just their interface, but that’s because I’m a low level programmer, not one who ‘programs against the interface’readonlytypes appear to initially pose a conflict, as you’ve described. “How can a readonly type have a setter which appears to modify it? Properties are like fields, and the fields can’t be assigned to.” As property setters inreadonlytypes are not forbidden outright, the user may come to one of two conclusions:reffield), presumably the same data returned by the paired getter.As you’ve said, it remains the burden of the proposal champions to make a compelling use-case for opening up of a restriction.
I believe this restriction only really affects developers who are trying to make ‘pointer-like’ structs and are also concerned with performance because their structs are ‘dereferenced’ repeatedly in hot loops. This is exactly the ECS (or structure of arrays) game development pattern which has risen in popularity in recent years. You can see other developers with the same scenario and motivation in https://github.com/dotnet/csharplang/discussions/2068
If the C# language team believes that allowing setters in
readonlystructs at all was a mistake, then the only argument that can be made is that they’re useful, but perhaps that’s not worth the cost of muddying the convention.Additional notes:
readonlymodifier is still helpful to type authors in ensuring they don’t accidentally mutate the struct when maintaining or adding members. Developers of ‘lightweight native resource handles’ may also wish to usereadonlyfor this reason.structmay wish to add thereadonlymodifier, not realising that it will affect consumers of their type in the rvalue case, as there are no other observable usability side-effects.readonlytypes, but ECS or other ‘handle’ structs would benefit heavily from allowing plugin authors to define extension properties on such handles when they also associate component data with those entities.Per @jaredpar, changing this now requires a discussion with a minispec. Championed: https://github.com/dotnet/csharplang/issues/9174
@Chicken-Bones has already given a good example as to why ref properties would not work, bit packing. Where the binary representation of data is not 1 to 1 with how the user should have to interact with it.
I have given the example of non garbage collected immutable handles that set and get values through interop, where you would clearly not want the value to be stored in the struct or have the ability to set the values directly via ref in the first place. Why would you not want to interact with verbose C getters and setters through beautiful, concise C# properties? Can you honestly say, as an api consumer, you would prefer methods over properties? Here’s a more concrete example in an audio library I’ve been tinkering with. As an example, moving a sound in 3d space would go from:
to
If you really think that methods are a better experience, either you’re joking or you may find this link useful.
I’m not sure if we’ve not been clear enough or perhaps we need the input of Microsoft developers with more diverse backgrounds in development.
IMO, if you have such a situation, writing methods seems entirely cromulent 😃
The benefit here is that if you have the normal property form the code looks entirely suspect/broken. In the examples, since a struct is returned, normal assumption is that that would be a copy. And so, mutating that copy is more often than not just a straight bug. Akin to getting a tuple as an rvalue and writing into it.
Methods much more clearly express: do unbounded work, including on data outside of the value. Properties that “call through” to some other store are the much less common case, and it seems fine to restrict those to catch the common case of this being a bug. Methods, on the other hand, allow you to express that something special can be going on, and have hte API stay aligned with the intent and clarity of the impl.
In our case, the
structbeingreadonlyis a performance detail for the jit and compiler, and the properties accessing an external (structure of arrays) data store is an implementation detail not relevant to the user.Users are not unfamiliar with structs being references to actual data (such as
Memory)And that’s why this is an antipattern. The code certainly gives that appearance. If you’re going to have a type that behaves in that way (where it doesn’t seem like it will mutate, but the code indicates it will), just don’t use a non-ref property for that. 😃
That’s why i said that this wasn’t a question of whether something could be allowed, but rather should it be allowed. This falls into the latter discussion. I completely understand the arguments of making this just about “could this be allowed”, but they’re falling flat for me because (like other examples provided in this thread) i think the additional guardrails are good things. Indeed, the examples given so far have reinforced that belief for me due to how wonky they actually appear.
I think this thread is lacking in real world examples that demonstrate why this change would be good. So far, all the examples have made me actually feel like we don’t go far enough in terms of blocking certain things.
If the intention is to discourage property setters on
readonly structtypes, surely it would make more sense to show the warning (or error) at the property definition, rather than showing an error when the property is used? The ‘crime’ has already been committed!This would also allow developers who feel this restriction is unnecessary (see upthread) to suppress the warning if it would be a false-positive in their case.
@CyrusNajmabadi It seems you entirely missed the point.
Correct
readonlyprevents defensive copies being created which would serve us no purpose.Originally,
Tilewas aclass, andTiles[x, y]always returned a reference to the same class. We had two issues with this approach, but performance and memory overhead was a primary concern. In an update ~2 years ago we changedTileto astructcontaining a single_indexand moved the data into arrays. This eliminated object overheads, and improved cache coherency.readonly struct Tileis effectively a validated reference, or a smart pointer, etc.Users understand that
Tilebeing a struct does not mean the effects of their setters are discarded. They can continue to write code as ifTilewas aclass. Moving them toGetColor()SetColor(Color color)method pairs provides no additional readability or clarity.I understand that seeing
c.Color = valuewherecis a local copy of astructraises some questions, but I believe that seeingc.SetColor(value)raises the exact same questions, and that these questions are quickly addressed by documentation.I understand that we need to consider some subset of possible ways to write C# to be ‘good/proper/intended’, so I respect the time you’re spending making this decision.
In my experience, one of the strengths of C# is that it provides tools to obtain better performance and implement closer to the metal, while retaining the safety of a managed language. I’ve always seen
structas primarily performance and native interop motivated, and recent focus onreffields indicates that this is an opinion shared by the language team.There was another alternative that I missed: return a ref from the property.
This seems to me like the least-bad way to work around CS1612 for the fake-indexed-property use case.
There is a concurrent discussion at https://github.com/dotnet/csharplang/discussions/2068; I chose to comment here however as there seemed to be more debate/discussion on this thread. Whether this warning/error change would be a change to the language or the compiler I’m not personally sure of, so I simply picked the more active thread.
I’m aware of the alternatives proposed but agree with the other commenters that they’re inadequate. MrBrixican’s comment above applies to my scenario as well (non-GCd immutable handles). The fact that they’re non-GCd immutable handles is not a detail I want users to have to know or care about. I wish to provide the illusion of regular mutable C# objects. However, this compiler error restricts that, forcing me to push a performance-oriented implementation detail on to the end-user.
Setter methods don’t address the concerns raised anyway. A “SetXyz(p)” method with void return and no other inputs by appearance alone still ostensibly mutates the instance; understanding that it does not requires an implicit understanding that the target struct is a convenience object wrapping a handle-- therefore the distinction between setter and set property is dubious at best. Consequently, I consider that alternative to be forcing an uglier anti-conventional pattern for no actual gain.
I would prefer CS1612 be there to help protect users against accidentally attempting to mutate rvalues, not to make judgement calls about the design of my API/library.
Yes, when dealing with readonly types and non-locations rvalues. But, personally, i wouldn’t make these readonly.
I think we need to review some statements in this issue so far:
This is not in line with the official C# language spec (§15.7.1):
Clearly, actions are very much included in the scope of property setters. Many dotnet classes make use of these “side-effects” for events/notifications. Look no further than some of the most used classes in enterprise settings:
DataTable,DataRowCollection, andDataRow(source).It has also been mentioned that a property setter that does not directly modify the item you’re calling it on is an anti-pattern:
On top of already contradicting §15.7.1 regarding no standardized storage location, this also contradicts with more Microsoft code:
FileStream.Positionsetter redirects toFileStreamStrategy.Position(source)ConsoleusesConsolePalin setters and getters (source)All of these were found after only a few minutes of searching, there are sure to be countless more contradictions.
All that is to say, code correctness is so subjective, it is not even worth discussing in this context. Let’s please stay on topic, this issue is not about good code, anti-patterns, or best practices. This is about an inconsistency in the way readonly struct property setters are treated by the compiler:
Cases 1 and 3 currently work, and given that breaking changes are generally avoided they will continue to work in future. It only makes logical sense then, to maintain consistency, cases 2 and 4 should also work.
Regardless of my own bias, I think it’s pretty obvious that removing this error in these cases will at the very least reduce confusion among developers which we’ve seen for the last 4 years.
However, I’m not on the boat of “fix it right now” and understand that the implementation to address this issue may be far more complex than many of us imagine. I just think it would be neat if this issue could be given a little more consideration. 😃
To me… that is the value 😃
It strongly pushes one down the path of only exposing in this fashion through either a method or a ref-property. Normal props are blocked off.
We have done so for other members, but some of them require a property to perform bitpacking. Whether a property getter returns a
refor whether the property has asetmethod is only identifiable by interrogating the underlying member, not from reading code in plain text. The use cases are often similar, though it remains that neither refs nor properties are first class language citizens yet.I understand your stance on properties behaving as fields rather than get/set methods. I think that allowing setters at all in
readonlystructs contradicts this, but perhaps it was too late to change.I believe further agreement could only be obtained by consulting more perspectives, as C# caters to a diverse set of users with different expectations and use cases.
I’d like to bump this one in the hopes of getting it out of backlog. I publish an API for a large community of users and this issue creates friction.
Simplified:
In other places we have been able to use
refreturns with get only properties, but here we need an actual property.Today, yeah, you either give up the indexer syntax and use a method or you give up being allocation-free and make the fake indexed property return a reference type or you give up the setter on the indexer and return a ref.
Given that the problem CS1612 is meant to protect against (mutating the copy of the struct returned by the property) can’t happen when the returned struct is readonly, it seems reasonable for the compiler to not produce the error.
I’d prefer that both compile. One example use case is implementing fake indexed properties:
(Edited to show more alternatives.)