Skip to content

BUG: CC0052 (Make readonly) should not be applied to complex value types #775

@kindermannhubert

Description

@kindermannhubert

Fix of this analyzer can be really dangerous when used on non-primitive value types.
As CC0052 was already restricted only to private fields, maybe it should be restricted further just to reference types and primitive value types (another aspect of readonly complex value types is that it can harm performace because at each access to field whole struct must be loaded on stack).

Here's an example of code which will break after changing field 'myStruct' to readonly:

public class MyClass
{
    private MyStruct myStruct = default(MyStruct);

    public void Modify()
    {
        myStruct.Modify();
        Console.Write(myStruct.Value);
    }

    private struct MyStruct
    {
        public int Value;

        public void Modify()
        {
            Value++;
        }
    }
}

public class Program
{
    private static void Main(string[] args)
    {
        var myClass = new MyClass();
        for (int i = 0; i < 5; i++)
        {
            myClass.Modify();
        }
    }
}

When 'myStruct' is not readonly output of program will be:
12345

but after making it readonly the out will be following:
00000

Another common example could be using System.Threading.SpinLock (it just doesn't work if it is saved in readonly field).

So, CC0052 should not be applied to complex value types. The above code should not raise CC0052. Instead, we will use a new diagnostic id: CS0121. The analyzer should be updated to use this new id. It should be on the same analyzer, a new one should not be created.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions