Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C#
Tip/Trick

Generic Event Handler Using Extension Method

Rate me:
Please Sign up or sign in to vote.
2.22/5 (4 votes)
31 Oct 2013CPOL 24.1K   4   20
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.

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am a Software Developer By Profession.

Comments and Discussions

 
GeneralMy vote of 1 Pin
Athari1-Nov-13 5:25
Athari1-Nov-13 5:25 
GeneralMy vote of 1 Pin
johannesnestler1-Nov-13 0:49
johannesnestler1-Nov-13 0:49 
QuestionThere is also a possibility for null exception there due to a well known race condition when dealing with events Pin
Sacha Barber31-Oct-13 7:03
Sacha Barber31-Oct-13 7:03 
AnswerRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
Athari31-Oct-13 9:58
Athari31-Oct-13 9:58 
GeneralRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
johannesnestler1-Nov-13 0:14
johannesnestler1-Nov-13 0:14 
GeneralRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
Athari1-Nov-13 2:48
Athari1-Nov-13 2:48 
GeneralRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
johannesnestler1-Nov-13 4:44
johannesnestler1-Nov-13 4:44 
GeneralRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
Athari1-Nov-13 5:03
Athari1-Nov-13 5:03 
GeneralRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
johannesnestler1-Nov-13 5:53
johannesnestler1-Nov-13 5:53 
GeneralRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
Athari1-Nov-13 6:31
Athari1-Nov-13 6:31 
Jon Skeet is StackOverflow's local god (he also wrote C# in Depth, is C# MVP etc.). He may have questionable preferences, but it doesn't make him wrong. It's not like I agree with everything even Eric Lippert says either, but I'm not pretending I'm smarter.

My points:
1. Delegates are immutable.
2. An argument passed by value is a local variable.
3. When you write changed += handler, you get a new delegate assigned to changed.
4. When you write if (changed != null) changed(...) and changed is an event field, it can become null between accesses, because the value of the field can be changed by another thread to another delegate or null.
5. When you write if (changed != null) changed(...) and changed is a local variable (or an argument passed by value), it cannot be changed from the outside between the accesses, because only one method has access to it and delegates are immutable.

The "VERY WELL KNOWN TOPIC" you refer to is #4. We're dealing with #5. Look at the code, it's not that hard.
“Today is the first day of the rest of your life.”

GeneralRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
johannesnestler1-Nov-13 8:34
johannesnestler1-Nov-13 8:34 
AnswerRe: There is also a possibility for null exception there due to a well known race condition when dealing with events Pin
Bheeshm31-Oct-13 16:49
professionalBheeshm31-Oct-13 16:49 
QuestionNot following the convention... Pin
johannesnestler31-Oct-13 5:57
johannesnestler31-Oct-13 5:57 
AnswerRe: Not following the convention... Pin
OriginalGriff31-Oct-13 6:37
mveOriginalGriff31-Oct-13 6:37 
AnswerRe: Not following the convention... Pin
Bheeshm31-Oct-13 16:55
professionalBheeshm31-Oct-13 16:55 
GeneralRe: Not following the convention... Pin
johannesnestler1-Nov-13 0:46
johannesnestler1-Nov-13 0:46 
GeneralRe: Not following the convention... Pin
Bheeshm1-Nov-13 2:23
professionalBheeshm1-Nov-13 2:23 
GeneralRe: Not following the convention... Pin
johannesnestler1-Nov-13 5:00
johannesnestler1-Nov-13 5:00 
GeneralRe: Not following the convention... Pin
Athari1-Nov-13 5:20
Athari1-Nov-13 5:20 
GeneralRe: Not following the convention... Pin
johannesnestler1-Nov-13 5:59
johannesnestler1-Nov-13 5:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.