Assigning a variable of a struct that contains an instance of a class to another variable

Posted by xport on Stack Overflow See other posts from Stack Overflow or by xport
Published on 2011-06-26T22:02:19Z Indexed on 2011/06/27 8:22 UTC
Read the original article Hit count: 247

Filed under:
|
|
|
|

In my understanding, assigning a variable of a struct to another variable of the same type will make a copy. But this rule seems broken as shown on the following figure. Could you explain why this happened?

enter image description here

using System;

namespace ReferenceInValue
{
    class Inner
    {
        public int data;
        public Inner(int data) { this.data = data; }
    }

    struct Outer
    {
        public Inner inner;
        public Outer(int data) { this.inner = new Inner(data); }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Outer p1 = new Outer(1);
            Outer p2 = p1;
            Console.WriteLine("p1:{0}, p2:{1}", p1.inner.data, p2.inner.data);


            p1.inner.data = 2;
            Console.WriteLine("p1:{0}, p2:{1}", p1.inner.data, p2.inner.data);


            p2.inner.data = 3;
            Console.WriteLine("p1:{0}, p2:{1}", p1.inner.data, p2.inner.data);

            Console.ReadKey();
        }
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about class