C# 11:
file class C
{
public int IntField1;
}
file struct S
{
public int IntField1;
}
file class StructureVsClassWhenCopying
{
private static void v1()
{
System.Console.WriteLine("v1");
}
private static void v2()
{
System.Console.WriteLine("v2");
}
public static void Main()
{
C c1 = new();
c1.IntField1 = 1;
C c2 = c1;
c1.IntField1 = 2;
System.Console.WriteLine(c2.IntField1); // 2, because class is a reference-type
S s1 = new();
s1.IntField1 = 1;
S s2 = s1;
s1.IntField1 = 2;
System.Console.WriteLine(s2.IntField1); // 1, because struct is a value type
string str1 = "old string";
string str2 = str1;
str1 = "new string";
System.Console.WriteLine(str2); // old string, because string is immutable
System.Action a1 = v1;
System.Action a2 = a1;
a1 -= v1;
a1 += v2;
a2.Invoke(); //v1. Why?
}
}
I want to know about the copying of reference and value types. I have understood this example with classes (reference type), struct (value types) and strings (also reference types, but immutable). But delegates also are reference types, why do thay behave like structs and strings?
Assigning
a1toa2means you are making a copy of the reference contained ina1, which is a reference tov1. At no point doesa2contain a reference toa1. So changinga1has no effect.