c#: create an event for when an object's field values change

Make it a property rather than a field, and implement INotifyPropertyChanged in your class :

class YourClass : INotifyPropertyChanged
{

    private int _number;
    public int Number
    {
        get { return _number; }
        private set
        {
            _number = value;
            OnPropertyChanged("Number");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

}

You can then listen explicitly for the PropertyChanged event, or use a data binding that will handle it automatically


You should use user-defined getters and setters (i.e. properties) to manually fire the event. Look at this code, it should be pretty simple:

// We declare a delegate to handle our event

delegate void StateChangedEventHandler(object sender, StateChangedEventArgs e);

// We declare event arguments class to specify, which value has changed to which value.

public class StateChangedEventArgs: EventArgs
{
    string propertyName;

    object oldValue;
    object newValue;

    /// <summary>
    /// This is a constructor.
    /// </summary>
    public StateChangedEventArgs(string propertyName, object oldValue, object newValue)
    {
        this.propertyName = propertyName;

        this.oldValue = oldValue;
        this.newValue = newValue;
    }
}

/// <summary>
/// Our class that we wish to notify of state changes.
/// </summary>
public class Widget
{
    private int x;

    public event StateChangedEventHandler StateChanged;

    // That is the user-defined property that fires the event manually;

    public int Widget_X
    {
        get { return x; }
        set
        {
            if (x != value)
            {
                int oldX = x;
                x = value;

                // The golden string which fires the event:
                if(StateChanged != null) StateChanged.Invoke(this, new StateChangedEventArgs("x", oldX, x);
            }
        }
    }
}

Our member variable is defined private, so no one outside of the class Widget can access it; they are forced to use the property Widget_X, and once they do, there are two cases:

  • They get the x variable. Nothing to do.
  • They set the x variable to the same value it had before. Nothing to do. We check it inside the setter.
  • They set the x variable and change it. That is where we fire the event.

It is critical to check if we have any event handlers registered (that is, our event is not null) before we ever invoke the event. In other case, we'll get an exception.

Tags:

C#

Object

Events