Feature Post

Top

C#: Adding Custom Event and EventHandler

Steps to write a custom event:

Quickest way to write a custom event:

1. Write a delegate event handler
2. Write an event
3. Write a method call

public delegate void NotificationEventHandler(object sender, string Message /*Notification Message*/);
public event NotificationEventHandler NotifyEvent;

private void OnNotify(string Message)
{
    NotificationEventHandler handler = NotifyEvent;
    if (handler != null)
    {
        handler(this, Message);
    }
}

In any method call, whenever something happens, call it method:

OnNotify("Some important Notification Message");

You can implement the EventArgs to have your own NotificationEventArgs, that may contain type of notification, and other information.

Custom Events Using Lamba Expression:
YourObject.OnNotify += (sender,"Test") => { MessageBox.Show("This is a test");};


Or, better add that into an Extension Method.

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


Following is how it would work, even for null events.

YourObject.Raise(this, EventArgs.Empty);

Or if you hate to check for nulls before using the events, instantiate your event with a delegate (tiny performance overhead).

public event EventHandler NotifyEvent = delegate{};