Mutating value types – Part 2

In the previous blog post, we found that mutating a struct inside a class works if the struct is declared as a field, but doesn’t work if it is declared as a property. The reason is fairly obvious – if struct fields also returned a copy, then there wouldn’t be any way of mutating the instance at all, even from within the declaring class. 1: struct S 2: { 3: public int X; 4: } 5: 6: class C 7: { 8: public S S; 9: 10: void SetX() 11: { 12: this.S.X = 1; // Won’t work if this.S … Continue reading Mutating value types – Part 2

Mutating value types – Part 1

Take a look at the following short snippet of code. 1: using System; 2: 3: struct S 4: { 5: public int X; 6: } 7: 8: class C 9: { 10: /* More code here */ 11: } 12: 13: class Test 14: { 15: public static void Main() 16: { 17: C c = new C(); 18: c.S.X = 1; 19: } 20: } Without knowing the type definition of C, can you tell whether the code will compile, much less work? Turns out that you can’t. It depends on whether the S in c.S is defined as … Continue reading Mutating value types – Part 1