Assigning a variable of a struct that contains an instance of a class to another variable
- by xport
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?
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();
}
}
}