CSharp - Delegate Create Events

Introduction

Events are associated with delegates.

Demo

using System;

class Publisher//from ww w  . j av a2 s .c  o m
{
    public delegate void JobDoneEventHandler(object sender, EventArgs args);
    public event JobDoneEventHandler JobDone;
    public void ProcessOneJob()
    {
        Console.WriteLine("Publisher:One Job is processed");
        OnJobDone();
    }
    protected virtual void OnJobDone()
    {
        if (JobDone != null)
            JobDone(this, EventArgs.Empty);
    }

}
class Subscriber
{
    public void OnJobDoneEventHandler(object sender, EventArgs args)
    {
        Console.WriteLine("Subscriber is notified");
    }
}
class Program
{
    static void Main(string[] args)
    {
        Publisher sender = new Publisher();
        Subscriber receiver = new Subscriber();
        sender.JobDone += receiver.OnJobDoneEventHandler;
        sender.ProcessOneJob();
    }
}

Result

Events are implemented as multicast delegates in C# and we can associate multiple event handlers to a single event.

Related Topic