user3370499
user3370499

Reputation: 15

Why is my array field changed when changing a memberwise clone of the instance?

A a = new A();
a.Inc2();

class A {
        public int[] i = {1,2,3};

    public int this[int index]{
        get { return i[index]; }
        set { i[index] = value; }
    }

    public static A Inc(A a) {
        a[0] = 666;
        return a;
    }

    public void Inc2() {
        A B  = A.Inc((A)this.MemberwiseClone());
        // WHY this[0] == 666????
    }
}

Why in "this[0]" I have 666? How can I get encapsulation in .

Upvotes: 0

Views: 73

Answers (1)

Trident D'Gao
Trident D'Gao

Reputation: 19762

MemberwiseClone makes a shallow copy

Upvotes: 2

Related Questions