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();
}
}
}
You answered your question in the topic.
Your structure contains a reference, when the structure is copied, it is copied as a chunk of memory, including the reference (not the object that is referenced), just as if the reference was an integer or another primitive.
Copying a structure does not cause cloning.
In fact, placing a reference in a structure is a bad idea and should be avoided. An exception to this is immutable reference objects (such as strings), which are "safe" to place in structures, since they can not be modified, however you will still loose locality in memory.
Remember, value types are stored locally in the scope of their definition, reference types are always stored on heap and a reference is stored locally in the scope of their definition.