I am starting to learn C# and could do with the following result explained to me regarding value types and reference types. My understanding is that ints and structs are value types so therefore get copied in assignments and strings and classes are reference types so only the reference is copied and not the underlying object. This is my code to test this:
struct MyStruct
{
public class C
{
public string _string;
};
public C _c;
public string _string;
public int _a;
public MyStruct(int a, string s)
{
_a = a;
_c = new C();
_c._string = s;
_string = s;
}
};
public static void Main(string[] args)
{
MyStruct stru = new MyStruct(4, "Hello");
MyStruct stru2 = stru;
stru2._a = 5;
stru2._string = "World";
stru2._c._string = "World";
Console.WriteLine("Stru _a: " + stru._a);
Console.WriteLine("Stru2 _a: " + stru2._a);
Console.WriteLine("Stru _string: " + stru._string);
Console.WriteLine("Stru2 _string: " + stru2._string);
Console.WriteLine("Stru C _string: " + stru._c._string);
Console.WriteLine("Stru2 C _string: " + stru2._c._string);
}
In this contrived example I get the following output:
Stru _a: 4
Stru2 _a: 5
Stru _string: Hello
Stru2 _string: World
Stru C _string: World
Stru2 C _string: World
The int variable _a makes perfect sense. It's a value type so it gets copied and not referenced, hence the change to "Stru2" doesn't effect "Stru". The _string surprised me as it's a reference type I expected both values to be output as "World". I expected the _c._string to both be "World" like it is, however I don't understand why the behaviour is different to the _string not part of the class. Any explanation would be appreciated. Thanks!