I have a property which is currently automatic.
public string MyProperty { get; set; }
However, I now need it to perform some action every time it changes, so I want to add logic to the setter. So I want to do something like:
public string MyProperty {
get;
set { PerformSomeAction(); }
}
However, this doesn't build... MyProperty.get' must declare a body because it is not marked abstract, extern, or partial
I can't just have the getter return MyProperty
as it will cause an infinite loop.
Is there a way of doing this, or do I have to declare a private variable to refer to? I'd rather not as MyProperty
is used through out the code both in this class and outside it
You need to use a property with backing field:
private string mMyProperty;
public string MyProperty
{
get { return mMyProperty; }
set
{
mMyProperty = value;
PerformSomeAction();
}
}