I want to use auto-implemented properties, but at the same time I want to call a method every time the property is changed.
public float inverseMass
{
get;
set
{
onMassChanged();
inverseMass = value;
}
}
Does the previous code make a recursive call to the property? If it does, how to implement this?
If you provide your own get/set then you need to provide your own storage for the variable.
private float _inverseMass;
public float inverseMass
{
get { return _inverseMass; }
set
{
_inverseMass = value;
onMassChanged();
}
}
Use a backing field instead:
public float inverseMass
{
get
{
return _inverseMass;
}
set
{
_inverseMass = value;
onMassChanged();
}
}
private float _inverseMass;
I once read somewhere that the C# guys decided that they wanted to cover the broad of the usage scenarios with those automatic properties, but for special cases you have to go back to good old backing fields.
(To be honest, I believe that Jon Skeet told them how to implement them)
You would need to break the above out in to private/public members so you don't get recursive problems:
private float _inverseMass;
public float inverseMass
{
get { return this._inverseMass; }
set { this._inverseMass = value; onMassChanged(); }
}
However, have you looked in to the INotifyPropertyChanged
interface? It does pretty much what you're looking for, and depending on what you're writing it could be supported natively.
public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String property)
{
var event = this.PropertyChanged;
if (event != null)
{
event(this, new PropertyChangedEventArgs(property));
}
}
private float _inverseMass;
public float inverseMass
{
get { return this._inverseMass; }
set { this._inverseMass = value; NotifyPropertyChanged("inverseMass"); }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With