简体   繁体   中英

Readonly vs static readonly clarification

I've run into an interesting situation I am trying to understand. I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.

That is not what I am observing. I only see the expected behavior with a static field. I expected the behavior for both types.

private struct junk
{
    public int i;

    public void change()
    {
        i += 1;
    }
}

private readonly junk jk;
private static readonly junk jk2;

public Form1()
{
    InitializeComponent();
    jk.change();
    //jk.i is now 1, why? Shouldn't it be changing a copy and not the original jk?
    jk2.change();
    //jk2.i is 0
}

I have a readonly struct field in my class. This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged.

That's not at all what the readonly modifier does. The readonly modifier prevents you from assigning a new value to jk anywhere but in a constructor. Then, the static modifier allows you to reuse that value independently of the instance of Form1 you are working with.
That said, neither readonly nor static is making the weird behavior you are describing because that exact behavior cannot be reproduced with the code you've posted.

Look at a simpler example in a Console application (which you can try here ):

public class Program
{
    private readonly junk jk;
    private static readonly junk jk2;

    public static void Main()
    {
        var program = new Program();
        program.jk.change();
        Console.WriteLine(program.jk.i); // prints 0

        jk2.change();
        Console.WriteLine(jk2.i); // prints 0
    }
}

public struct junk
{
    public int i;
    public void change()
    {
        i += 1;
    }
}

Then, as @Damien_The_Unbeliever commented, try to avoid mutable struct s as much as you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM