Monday, January 28, 2019

C# EventHandler Example

Contact Class


public class PhoneNumberChangedEventArgs : EventArgs
{
    public PhoneNumberChangedEventArgs(string oldPhoneNumber, string newPhoneNumber)
    {
        OldPhoneNumber = oldPhoneNumber;
        NewPhoneNumber = newPhoneNumber;
    }
    public string OldPhoneNumber { get; }
    public string NewPhoneNumber { get; }
}
public class Contact
{
    public event EventHandler<PhoneNumberChangedEventArgs> PhoneNumberChanged;
    public Contact(string phoneNumber)
    {
        _phone = phoneNumber;
    }
    private string _phone;
    public string PhoneNumber
    {
        get { return _phone; }
        set
        {
            if (value != _phone)
            {
                var _oldPhone = _phone;
                _phone = value;
                OnPhoneNumberChanged(new PhoneNumberChangedEventArgs(_oldPhone, value));
            }
        }
    }
    protected virtual void OnPhoneNumberChanged(PhoneNumberChangedEventArgs e)
    {
        PhoneNumberChanged?.Invoke(this, e);
    }
}

Example Usage


EventHandler<PhoneNumberChangedEventArgs> handler = (object sender, 
    PhoneNumberChangedEventArgs e) =>
{
    Console.WriteLine("Phone number changed from {0} to {1}!",
        e.OldPhoneNumber, e.NewPhoneNumber);
};

var c = new Contact("555-555-1234");
c.PhoneNumberChanged += handler;
c.PhoneNumber = "555-555-6789";
c.PhoneNumberChanged -= handler;
This will generate the following output:

Phone number changed from 555-555-1234 to 555-555-6789!