regev


Comments:

C# Structs

posted by regevregev(20) 3 years, 6 months ago 0

Another implication of the stack versus heap issue might be surprising to some. Consider the following:
I declare a struct:

struct A
{
public bool B;
}

Now guess what will happen if try to use it as follows:

A a = new A(); // Create an instance.
List<A> list = new List<A>();
list.Add(a); // Add to a list.
list[0].B = false; // Change the bool value.

What happens is compilation error on the last line! The error will not happen if I use class instead of struct:

class A
{
public bool B;
}


Have a nice day.
;)

Reply