Pages

Saturday, September 22, 2012

C# Custom Event Handling

There are a lot of examples on Event Handling and delegates in C# on the net, but most of them are just too complicated and confusing for a beginner. Today I'd like to share with you simple and clear example of event handling with custom event arguments.

Imaging that we have a simple Employee class. There are two properties - Name and Salary. We want a mechanism that will indicate that employee's salary has changed.Obviously we need create an event inside our Employee class and fire it each time when salary has changed.
Let's see Employee class source code:
public class Employee
{
    public delegate void PropertyChangedHandler(object sender, PropertyChangeEventArgs args);

    public event PropertyChangedHandler PropertyChange;

    public void OnPropertyChange(object sender, PropertyChangeEventArgs args)
    {
        // If there exist any subscribers call the event
        if (PropertyChange != null)
        {                
            PropertyChange(this, args);
        }
    }

    public string Name { get; set; }

    private int _salary = 5000;
    public int Salary
    {
        get { return _salary; }
        set
        {
            int oldValue = _salary;
            _salary = value;
            OnPropertyChange(this, new PropertyChangeEventArgs("Salary", value - oldValue));
        }
    }
}
PropertyChange is actually our event. PropertyChangeHandler delegate will allow us to subscribe to the event from other classes. We also want to pass custom arguments to subscriber, namely the difference between old amount of salary and the new one. That's why second parameter of the delegate is not EventArgs, as usual, but our custom class PropertyChangeEventArgs.
Let's see PropertyChangeEventArgs class source code:
public class PropertyChangeEventArgs : EventArgs
{
    public string PropertyName { get; internal set; }        
    public int Difference { get; internal set; }

    public PropertyChangeEventArgs(string propertyName, int difference)
    {
        PropertyName = propertyName;            
        Difference = difference;
    }
}
Now let's see how to subscribe to our event from other class:
class Program
{
    static void Main(string[] args)
    {
        Employee employee = new Employee();
        employee.PropertyChange += new Employee.PropertyChangedHandler(PropertyChanged);
        employee.Salary = 8000;            
        Console.ReadLine();
    }
    
    public static void PropertyChanged(object sender, PropertyChangeEventArgs args)
    {
        if (args.PropertyName == "Salary")
        {
            Console.WriteLine("Salary amount has changed! Salary difference is : " 
                               + args.Difference.ToString());
        }
    }
}
Here is the output:
Event Handling example output

Download the source code (Visual Studio 2010 project).

3 comments:

  1. Loved the simplicity!!!

    ReplyDelete
  2. I'm getting a build error on the PropertyChange stating that the PropertyChange must be on the left side of either += or -=. Any idea what I'm doing wrong?


    public void OnPropertyChange(object sender, PropertyChangeEventArgs args)
    {
    // If there exist any subscribers call the event
    if (PropertyChange != null)
    {
    PropertyChange(this, args);
    }
    }

    ReplyDelete