I know that when it comes to references types (ie: classes), changes to properties of said reference types are persisted across method calls, regardless of the type of the property.
I recently noticed that the same is not true for value types (ie: structs). That is, changes to properties of value types are persisted across method calls only if said properties are non-built in reference types.
For example:
Code:
namespace N
{
class M
{
public int k = 0;
}
class C
{
public string s;
public int i;
public M m;
public C(string s, int i, M m)
{
this.s = s;
this.i = i;
this.m = m;
}
}
struct S
{
public string s;
public int i;
public M m;
public S(string s, int i, M m)
{
this.s = s;
this.i = i;
this.m = m;
}
}
class Program
{
static void Main()
{
C c = new C("A", 0, new M());
S s = new S("A", 0, new M());
Console.WriteLine(c.s + ", " + c.i + ", " + c.m.k); //A, 0, 0
Console.WriteLine(s.s + ", " + s.i + ", " + s.m.k); //A, 0, 0
Change(c);
Change(s);
Console.WriteLine(c.s + ", " + c.i + ", " + c.m.k); //AA, 1, 1
Console.WriteLine(s.s + ", " + s.i + ", " + s.m.k); //A, 0, 1
Console.ReadKey();
}
static void Change(C x)
{
x.s = "AA";
x.i++;
x.m.k++;
}
static void Change(S x)
{
x.s = "AA";
x.i++;
x.m.k++;
}
}
}
Not sure if the above code will compile (maybe I made typos somewhere ). But if it does compile you will find that changes to properties of value types persisted across method calls only in cases where those properties are non-built-in reference types. How come?