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));
}
}
}