Why do properties behave this way?

Posted by acidzombie24 on Stack Overflow See other posts from Stack Overflow or by acidzombie24
Published on 2010-04-12T01:34:32Z Indexed on 2010/04/12 1:43 UTC
Read the original article Hit count: 419

Filed under:
|
|

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

Error   1   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 property 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 cant imagine ever wanting the 2nd much less then the first. It is just so weird to me.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET