roslyn: "Make field readonly" should not fire if the field is a non-readonly struct and there are invocations on it

“Make field readonly” should not be offered on a field whose type is a non-readonly struct if there are any invocations or property accesses to the field. Doing so is very dangerous because it silently changes semantics from invoking a method on the original field to invoking it on a copy. Example of bad behavior:

using System;

struct S
{
    public readonly int Value;

    public S(int value) => this.Value = value;

    public void Mutate()
    {
        this = new S(Value + 1);
    }
}

static class C
{
    static S v;

    static void Main()
    {
        v.Mutate();
        Console.WriteLine(v.Value);
    }
}

This program prints 1, but if we make the field readonly, it prints 0.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 16 (16 by maintainers)

Most upvoted comments

This will fix the false positive mentioned, but it’s going to cause a bunch of new false negatives

Agreed. I’d be willing to accept the feature not being perfect, but being good enough for the vast majority of coding patterns out there.

@Neme12 Yep, I saw the commentary after I posted 👍