Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simplest event delegate ever

0.00/5 (No votes)
10 Oct 2006 1  
The simplest sample of how an event delegate can be used in C#.

Introduction

Check out this simple event delegate code. First, you have a source which generates an event:

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

namespace eventDelegate
{
    class Source
    {
        public event EventHandler SomeEvent; 
        // this event is of type EventHandler, 
        // meaning it can notify any function whose signature is like the 
        // one of EventHandler EventHandler is the delegate

        public void RaiseEvent()
        {
            if (null != SomeEvent) // to avoid exceptions when event 
            {                      // delegate wiring is not done
                SomeEvent(this, null);
            }
        }
    }
}

Next, you have a receiver which is supposed to get a notification of the event:

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

namespace eventDelegate
{
    class Receiver
    {
        public void NotifyMe(object source, EventArgs e)
        {
            Console.WriteLine("I am notified by "+source.GetType());
        }
    }
}

Then you have the main program which does the wiring:

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

namespace eventDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            Source theSource = new Source();
            Receiver theReceiver = new Receiver();

            theSource.SomeEvent += new EventHandler(theReceiver.NotifyMe);

            theSource.RaiseEvent();
        }
    }
}

As simple as that. It can now be extended to include custom event data and therefore a new class inheriting from EventArgs and therefore ending up with a new delegate which can handle this new EventArgs.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here