0

It's said, a best practice is to make structs immutable, so I did this:

struct MyStruct
{
    public int mI;
    public string mS;
}
[ImmutableObject(true)]
struct ComplexStruct
{
    public int mJ;
    public MyStruct st;
}

And the in main:

ComplexStruct cs = new ComplexStruct
{
    mJ = 6,
    st = new MyStruct
    {
        mI = 7,
        mS = "immutable"
    }
};
cs.st.mS = "Changed";
Console.WriteLine(cs.st.mS);
cs.st = new MyStruct
{
    mI = 8,
    mS = "check immutable?"
};

It compiles and runs well. What I expected is:

  1. cs.st is a struct, and changing the cs.st.mS is using a copy of the value, and the content should not change to "Changed"?

  2. I used Immutable attribute on "ComplexStruct", why still after initialization, I can change the "st" member struct?

I expected that compilation should fail, or there's runtime exception, because of using "Immutable". So why they don't work?

Thanks a lot.

Troskyvs
  • 7,537
  • 7
  • 47
  • 115
  • What does `ImmutableObject` do? Does it **document** what you have done? Or does it **do** something? – mjwills Jun 11 '19 at 09:36
  • If you want an immutable object then don't use fields, use properties with a private setter and initialise them in the constructor. Voila, immutable objects. – Steve Todd Jun 11 '19 at 09:40
  • I can see how it could confuse a developer that's inexperienced with the .Net framework, but the linked answer can help explain the point of this attribute. – Zohar Peled Jun 11 '19 at 09:42
  • 1
    @SteveTodd private setters does not make an object immutable. Missing setters do. – Zohar Peled Jun 11 '19 at 09:43
  • [Immutable struct](https://stackoverflow.com/q/36780200/1997232). – Sinatr Jun 11 '19 at 10:24

0 Answers0