how to override set in C# of automatic properties
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"); }
}
}