Generic Event Handler Using Extension Method

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

    }

 }

}

Ebook Download
View all
Learn
View all