From http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx
using System;
struct MutableStruct
{
public int Value { get; set; }
public void SetValue(int newValue)
{
Value = newValue;
}
}
class MutableStructHolder
{
public MutableStruct Field;
public MutableStruct Property { get; set; }
}
class Test
{
static void Main(string[] args)
{
MutableStructHolder holder = new MutableStructHolder();
// Affects the value of holder.Field
holder.Field.SetValue(10);
// Retrieves holder.Property as a copy and changes the copy
holder.Property.SetValue(10);
Console.WriteLine(holder.Field.Value);
Console.WriteLine(holder.Property.Value);
}
}
1) Why is a copy (of Property?) being made?
2) When changing the code to holder.Field.Value
and holder.Property.Value = 10
, I get the error below. That just blew my mind.
Cannot modify the return value of 'MutableStructHolder.Property' because it is not a variable
Why would I ever not be allowed to assign a value inside of a property!?! Both properties are get
/set
!
And finally WHY would you EVER want behavior mentioned in 1 and 2? (It never came up for me, I always used get only properties).
Please explain well, I can't imagine ever wanting the 2nd much less then the first. It is just so weird to me.