Events are mechanisms that allow application-specific code to execute when an action occurs. In Microsoft .Net Framework events are implemented using delegate (the event handler).

A delegate is a reference type that can be used to encapsulate a method with a specific signature and lets you pass a function as a parameter in type-safe manner.

The event-handler signature observes the following conventions:

  • void return type;
  • the first parameter is named sender and is of type object. This is the object that raised the event.
  • the second parameter is named e and is of type EventArgs or a derived class of EventArgs. This is the event-specific data.

Example:

delegate void sampleEventHandler (object sender, EventArgs e);

At this point you can define your event of the type of the declared delegate:

public event sampleEventHandler SampleEvent;


Instead of manually create your specific delegate as event-handler, you can use the generic System.EventHandler<T>, where T is of type EventArgs or a derived class of EventArgs:

public event EventHandler<SampleEventArgs> SampleEvent;

To fire (raise) the event, normally is used a notifier method. For convention is a protected virtual method with the same name of the event plus the suffix "On" (ex. OnSampleEvent for the event SampleEvent):

protected void OnSampleEvent(SampleEventArgs e)
{
    if (this.SampleEvent != null) this.SampleEvent(this, e);
}


To consume the event, the client must subscribe the event passing a pointer to a method with the same signature of the event-handler delegate.


Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        EventSource es = new EventSource();

        // subscribe the event
        es.SampleEvent += EventSource_SampleEvent;

        // Do the work
        es.DoWork();

        // unsubscribe the event
        es.SampleEvent -= EventSource_SampleEvent;

        Console.WriteLine("Press ENTER to quit");
        Console.ReadLine();
    }


    static void EventSource_SampleEvent(object sender, SampleEventArgs e)
    {
        Console.WriteLine("Current value: " + e.CurrentValue.ToString());
    }
}

// Event Source
public class EventSource
{
    // Event
    public event EventHandler<SampleEventArgs> SampleEvent;

    public EventSource()
    { }

    public void DoWork()
    {
        for (int i = 0; i < 10; i++)
        {
       
    OnSampleEvent(new SampleEventArgs(i));
        }
    }

    // Notifier
    protected virtual void OnSampleEvent(SampleEventArgs e)
    {
        if (this.SampleEvent != null)
this.SampleEvent(this, e);
    }
}

// Event Args
public class SampleEventArgs : System.EventArgs
{
    private int _CurrentValue;

    public int CurrentValue
    {
        get { return _CurrentValue; }
    }

    public SampleEventArgs(int value)
    {
        _CurrentValue = value;
    }
}