I have a property which is currently automatic.
public string MyProperty { get; set; }
However, I now need it to perform some action every
You need to use a property with backing field:
private string mMyProperty;
public string MyProperty
{
get { return mMyProperty; }
set
{
mMyProperty = value;
PerformSomeAction();
}
}
This is similar to the question C# getter and setter shorthand.
When you manually specify a setter, it won't use the automatic property mechanism for the getter, which is why the error message acts like it's missing. You'll need to write your own getter when you specify the setter.
You need to either provide a body for both the getter and setter, or neither.
So if you define either one, it's no longer an auto property.
So you have to do:
Either
public string MyProperty {
get;
set;
}// Automatic property, no implementation
OR
public string MyProperty
{
get { return mMyProperty; }
set
{
mMyProperty = value;
PerformSomeAction();
}
}
If you are doing something in the setter then you will have to explicitly declare the variable. E.g.
private string _myProperty;
public string MyProperty {
get { return _myProperty; };
set
{
_myProperty = value;
PerformSomeAction();
}
}
or - in the setter you can pass value to the function and do what you want to it there... assuming you want to change/check the value in the function PerformSomeAction()
You can´t implement one without the other, as when using the one it refers to a (hidden) backing-field which is auto-generated in the case of an autogenerated property. However when you implement one you have to set this backing-field in both ways.
The auto-way is just a shortcut for this:
private string _property;
public string MyProperty
{
get { return _property; }
set { _property = value; }
}
So if you´d omit the hidden field in one of the methods (this is what getters and setters are actually) how should this method know how to store/get the value?