Auto property value not updated with Struct

Take the following class struct:

public struct SingleWraper
{
    private double _myValue;

    public double MyValue
    {
        get { return _myValue; }
        set { _myValue = value; }
    }

    public void SetMyValue(double myValue)
    {
        _myValue = myValue;
    }
}

public struct DoubleWraper
{
    public SingleWraper SingWraper { get; set; }

    public void SetMyValue(double singleVa)
    {
        SingWraper.SetMyValue(singleVa);
    }
}

Perform the following test:

    [Test]
    public void SetMyValue()
    {
        var singleWraper = new DoubleWraper();
        singleWraper.SetMyValue(10);
        Assert.AreEqual(10,singleWraper.SingWraper.MyValue);
    }

Fails.

However, if you do not use the automatic property for DoubleWraper, that is, you expand the field as shown below:

public struct DoubleWraper
{
    private SingleWraper _singWraper;
    public SingleWraper SingWraper
    {
        get { return _singWraper; }
        set { _singWraper = value; }
    }

    public void SetMyValue(double singleVa)
    {
        _singWraper.SetMyValue(singleVa);
    }
}

Then the test will pass.

Why is this so?

+3
source share
1 answer

Here:

_singWraper.SetMyValue(singleVa);

vs

SingWraper.SetMyValue(singleVa);

In the second, you get access to the property , so you clone the structure; essentially this is the same as:

var clonedAndIndependentValue = SingWraper; // getter
clonedAndIndependentValue.SetMyValue(singleVa);

Note that we have updated a different structure value; contrasts with access to fields, which speaks of the value of the existing one .

, . . ( Set* , ). .

+7

Source: https://habr.com/ru/post/1730379/


All Articles