Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to override set in C# of automatic properties

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?

like image 423
MhdSyrwan Avatar asked Jan 03 '12 20:01

MhdSyrwan


3 Answers

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();
    }
}
like image 110
Gary Avatar answered Nov 06 '22 08:11

Gary


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)

like image 42
Uwe Keim Avatar answered Nov 06 '22 07:11

Uwe Keim


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"); }
  }
}
like image 5
Brad Christie Avatar answered Nov 06 '22 08:11

Brad Christie