Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Generic Event Handler Using Extension Method

0.00/5 (No votes)
31 Oct 2013 1  
A handy approach to raise events.

Introduction

Very often we need to invoke events, usually in Model classes , where we set some property and raise an event in order to notify any listeners. 

Using the code

Following is a full length example of 'How to use a Generic Event Handler to Raise an Event'.

It is good to have some helper (extension) method that can be used at various places, thus reducing the amount of code and making it quite maintainable.

using System;
using ExtensionHelper;

namespace EventHandlers
{
    public class MyModel
    {
        private string _name;
        private int _age;
        private decimal _salary;

        MyModel() { }

        public string Name
        {
            get { return _name; }
            set 
            {
                _name = value;
                NameChanged.Raise(this, EventArgs.Empty);
            }
        }

        public int Age 
        { 
            get { return _age; } 
            set 
            {
                _age = value;
                AgeChanged.Raise(this, EventArgs.Empty);
            } 
        }

        public decimal Salary 
        { 
            get { return _salary; } 
            set 
            { 
                _salary = value;
                SalaryChanged.Raise(this, EventArgs.Empty);
            }
        }

        public EventHandler NameChanged;
        public EventHandler AgeChanged;
        public EventHandler SalaryChanged;

    }

}

namespace ExtensionHelper
{
    public static void Raise(this EventHandler eventHandler, object sender, EventArgs e)
    {
        if (eventHandler != null)
        {
             eventHandler(sender, e);
        }
    }

    public static void Raise<T>(this EventHandler<T> eventHandler, 
           object sender, T e) where T : EventArgs
    {
        if (eventHandler != null)
        {
            eventHandler(sender, e);
        }
    }
}

History

This is my first article on CodeProject, and I am using the above mentioned code in my current assignments.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here