Calling a property setter when changing a (nested) property inside the property object

insane title . . I know . . but bear with me . .

consider the following case:

a.ClassProperty.ValueProperty = 4;

where:

class A
{
    [...]
    public PropertyClass ClassProperty
    {
        get { return new PropertyClass(m_someInformation); }
        set { ComplexMultistepSetInformation(m_someInformation); }
    }
    [...]
}

and:

class PropertyClass
{
    [...]
    public int ValueProperty { get; set; }
    [...]
}

My problem: when executing the first given statement the code will return a PropertyClass object and change the 'ValueProperty' in it, but the information itself for 'a' will remain the same.
What I would like to have is for the setter of 'ClassProperty' being called, after changing the information of the PropertyClass object retrieved via the 'ClassProperty' getter. Meaning, a way to make the first line accomplish the following:

PropertyClass tmp = a.ClassProperty;
tmp.ValueProperty = 4;
a.ClassProperty = tmp;

Is there any way to change the getters and setters around to accomplish it.

(Additional information: having a PropertyClass object in class A would not help. In the real use case PropertyClass is a wrapper around native code, simplifying access to variables and providing several extension methods, while information for a native object gets 'written' by the setter of property 'ClassProperty')

Jon Skeet
people
quotationmark

Is there any way to change the getters and setters around to accomplish it.

No, not really. The code:

a.ClassProperty.ValueProperty = 4;

is simply translated into:

var tmp = a.ClassProperty;
tmp.ValueProperty = 4;

It's never going to try to call the a.ClassProperty setter.

You might want to change to something like:

a.ModifyClassProperty(x => x.ValueProperty = 4);

Where ModifyClassProperty would effectively do:

  • Fetch information
  • Applied user-supplied delegate to it
  • Perform any steps to apply the changes to the underlying data

For example, you could achieve it with your current code:

void ModifyClassProperty(Action<PropertyClass> action)
{
    var tmp = ClassProperty;
    action(tmp);
    ClassProperty = tmp;
}

people

See more on this question at Stackoverflow