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)

Most upvoted comments

Yes, when dealing with readonly types and non-locations rvalues. But, personally, i wouldn’t make these readonly.

This depends on what the purpose of the readonly modifier on types is. As it stands, there are multiple purposes which aren’t fully aligned, the result of which is friction here.

  1. Preventing the modification of the values of fields in the type. Providing a guard rail for developers working on the type.
  2. Signalling to consumers of the type, that none of the properties or methods on the type can modify the values of its fields.
  3. Allowing the compiler to eliminate defensive copies.

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 readonly modifier from my struct.

Regarding purpose 2, the convention:

  • I expect relatively few consumers of struct types will check the definition to see the readonly modifier.
  • Unlike ref it 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’
  • Property setters on readonly types 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 in readonly types are not forbidden outright, the user may come to one of two conclusions:
    • The property setter mutates some other data, which is referenced by but not literally held in the struct (in a similar manner to assigning to a ref field), presumably the same data returned by the paired getter.
    • The property setter is unsafe/erroneous
    • or they may just remain confused.

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 readonly structs 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:

  • Even if the compiler didn’t eliminate defensive copies, the readonly modifier 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 use readonly for this reason.
    • Developers who have only exposed properties on their struct may wish to add the readonly modifier, not realising that it will affect consumers of their type in the rvalue case, as there are no other observable usability side-effects.
  • If the ‘extension everything’ or ‘roles’ proposals are eventually implemented, there would be further motivation for revisiting this limitation. Perhaps extension setters would be forbidden on readonly types, 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

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. 😃

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.

@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:

this.Music.Position += new Vector3(1f);

to

this.Music.SetPosition(this.Music.GetPosition() + new Vector3(1f));

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.

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.

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 struct being readonly is 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)

In my previous examples, was the struct ever “modified”? No.

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. 😃

Non-auto-property setters have no enforced or implied implementation regarding storage location

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.

This truly feels like an abuse of structs, indexers, and properties, as far as .Net and C# want them to be considered.

If the intention is to discourage property setters on readonly struct types, 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 readonly prevents defensive copies being created which would serve us no purpose.

Originally, Tile was a class, and Tiles[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 changed Tile to a struct containing a single _index and moved the data into arrays. This eliminated object overheads, and improved cache coherency. readonly struct Tile is effectively a validated reference, or a smart pointer, etc.

Users understand that Tile being a struct does not mean the effects of their setters are discarded. They can continue to write code as if Tile was a class. Moving them to GetColor() SetColor(Color color) method pairs provides no additional readability or clarity.

I understand that seeing c.Color = value where c is a local copy of a struct raises some questions, but I believe that seeing c.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 struct as primarily performance and native interop motivated, and recent focus on ref fields indicates that this is an opinion shared by the language team.

There was another alternative that I missed: return a ref from the property.

public sealed class Example
{
    private readonly int[] _indexedPropertyValues = new int[1];

    private readonly IndexedPropertyValues _indexedProperty;

    public Example()
    {
        _indexedProperty = new IndexedPropertyValues(this);
    }

    public ref readonly IndexedPropertyValues IndexedProperty => ref _indexedProperty;

    public readonly struct IndexedPropertyValues
    {
        private readonly Example _this;

        internal IndexedPropertyValues(Example @this)
        {
            _this = @this;
        }

        public int this[int index]
        {
            get => _this._indexedPropertyValues[index];
            set => _this._indexedPropertyValues[index] = value;
        }
    }
}

public static class Program
{
    public static void Main()
    {
        var example = new Example();

        example.IndexedProperty[0] = 1;
    }
}

This seems to me like the least-bad way to work around CS1612 for the fake-indexed-property use case.

Petitioning to change the language is required here. The compiler just implements the rules we language designers think are appropriate for the language.

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.

That’s a virtue if the particular design pattern is not viewed positively. See the above conversations for alternate approaches we think should be used instead.

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.

Can you honestly say, as an api consumer, you would prefer methods over properties?

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:

As methods are in the space of doing anything desired, whereas properties very much are designed such that they can be thought of as fields, just with computation being allowed on them.

This is not in line with the official C# language spec (§15.7.1):

However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written. Properties thus provide a mechanism for associating actions with the reading and writing of an object’s characteristics;

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, and DataRow (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:

And a setter which isn’t actually mutating the thing you’re calling on is the anti-pattern, and is much more cleanly and clearly expressed as a method call.

On top of already contradicting §15.7.1 regarding no standardized storage location, this also contradicts with more Microsoft code:

  • FileStream.Position setter redirects to FileStreamStrategy.Position (source)
  • Console uses ConsolePal in 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:

internal class Program
{
    ReadonlyStruct PropertyReadonlyStruct { get; set; }
    ReadonlyStruct FieldReadonlyStruct;
    ReadonlyStruct GetReadonlyStruct() => PropertyReadonlyStruct;
    ReadonlyStruct this[int index] => PropertyReadonlyStruct;

    void Main()
    {
        FieldReadonlyStruct.Data = 0;     // Case 1: no issue
        PropertyReadonlyStruct.Data = 0;  // Case 2: CS1612
        GetReadonlyStruct().Data = 0;     // Case 3: no issue
        this[0].Data = 0;                 // Case 4: CS1612
    }

    public readonly struct ReadonlyStruct
    {
        public int Data { get => 0; set { /* no-op */ } } // Note no mutation of ReadonlyStruct instance
    }
}

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. 😃

All it did was require you have something to ref that you otherwise might not have needed.

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.

but I believe that seeing c.SetColor(value) raises the exact same questions

It raises no questions for me. As methods are in the space of doing anything desired, whereas properties very much are designed such that they can be thought of as fields, just with computation being allowed on them.

Can you just expose this as a ref?

We have done so for other members, but some of them require a property to perform bitpacking. Whether a property getter returns a ref or whether the property has a set method 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 readonly structs 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:

public readonly struct Tile
{
	private readonly uint _index;
	public byte TileColor { get => ...; set => ...; }
	...
}

public readonly struct Tilemap
{
	public Tile this[int x, int y] => ...
}

// Cannot write
Tiles[x, y].TileColor = 0;

// Have to write
Tile t = Tiles[x, y];
t.TileColor = 0;

In other places we have been able to use ref returns 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.)

public sealed class Example
{
    private readonly int[] _indexedPropertyValues = new int[1];

    public IndexedPropertyValues IndexedProperty => new IndexedPropertyValues(this);

    public IndexedPropertyValues IndexedProperty2() => new IndexedPropertyValues(this);

    public ref int IndexedProperty3(int index) => ref _indexedPropertyValues[index];

    public IndexedProperty4Values IndexedProperty4 => new IndexedProperty4Values(this);

    public readonly struct IndexedPropertyValues
    {
        private readonly Example _this;

        internal IndexedPropertyValues(Example @this)
        {
            _this = @this;
        }

        public int this[int index]
        {
            get => _this._indexedPropertyValues[index];
            set => _this._indexedPropertyValues[index] = value;
        }
    }

    public readonly struct IndexedProperty4Values
    {
        private readonly Example _this;

        internal IndexedProperty4Values(Example @this)
        {
            _this = @this;
        }

        public ref int this[int index] => ref _this._indexedPropertyValues[index];
    }
}

public static class Program
{
    public static void Main(string[] args)
    {
        var example = new Example();

        example.IndexedProperty[0] = 1;  // CS1612

        ((Example.IndexedPropertyValues)example.IndexedProperty)[0] = 1;  // Okay (but ugly)

        example.IndexedProperty2()[0] = 1;  // Okay (but ugly)

        example.IndexedProperty3(0) = 1;  // Okay (but ugly and can't validate value)

        example.IndexedProperty4[0] = 1;  // Okay (but can't validate value)
    }
}