Apologies for not using a comment, I don't think it will fit.
Jon, this is not an actual implementation, I'm just trying to get a deeper understanding of structs, so no worries about me implementing mutable structs :)
Anyway, I'm not sure you are correct. Consider this code, it's almost the same as first example:
public struct SomeStruct
{
public int PublicProperty { get; set; }
public int PublicField;
public SomeStruct(int propertyValue, int fieldValue)
: this()
{
PublicProperty = propertyValue;
PublicField = fieldValue;
}
public int GetProperty()
{
return PublicProperty;
}
public void SetProperty(int value)
{
PublicProperty = value;
}
}
class Program
{
static void Main(string[] args)
{
SomeStruct a = new SomeStruct(1, 1);
a.PublicProperty++;
a.SetProperty(a.GetProperty()+1);
}
}
Now, looking at the msil using ildasm, gives me the following for the Main method:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 45 (0x2d)
.maxstack 3
.locals init ([0] valuetype ConsoleApplication1.SomeStruct a)
IL_0000: nop
IL_0001: ldloca.s a
IL_0003: ldc.i4.1
IL_0004: ldc.i4.1
IL_0005: call instance void ConsoleApplication1.SomeStruct::.ctor(int32,
int32)
IL_000a: nop
IL_000b: ldloca.s a
IL_000d: dup
IL_000e: call instance int32
ConsoleApplication1.SomeStruct::get_PublicProperty()
IL_0013: ldc.i4.1
IL_0014: add
IL_0015: call instance void
ConsoleApplication1.SomeStruct::set_PublicProperty(int32)
IL_001a: nop
IL_001b: ldloca.s a
IL_001d: ldloca.s a
IL_001f: call instance int32 ConsoleApplication1.SomeStruct::GetProperty()
IL_0024: ldc.i4.1
IL_0025: add
IL_0026: call instance void ConsoleApplication1.SomeStruct::SetProperty(int32)
IL_002b: nop
IL_002c: ret
}
I apologize for the terrible formatting, I'm not sure how to make it look normal. Anyway, hopefully, you can see that the last 2 lines of code in the main method are actually identical.
Therefore, I would argue that, from the previous post, this line:
a.OtherStruct.PublicProperty++;
Is actually identical to the line after it:
a.OtherStruct.SetProperty(a.OtherStruct.GetProperty() + 1);
And therefore it seems to me that the first line does not compile simply because the compiler does not support it, not because it is not legal.
What do you think?