C# Events


Events in C# are similar to exceptions in that they are raised (thrown) by objects and you can supply code that acts on them. There is no try…catch structure for events. You must subscribe to them. Subscribing to an event means that you must supply code that will be executed when an event is raised, in the form of an event handler. Subscribing to an event means to listen for it.

Many handlers can be subscribed to a single event, all of which are called when the event is raised. This can include event handlers that are part of the class of the object that raises the event, but event handlers are just as likely to be found in other classes. So, a single event is always raised by a single object, but a single event can be responded to by multiple objects.

Event handlers themselves are simply methods. The only restriction on an event handler method is that it must match the return type and parameters required by the event. This restriction is part of the definition of an event and is specified by a delegate.

...
using System.Timers;
using static System.Console;

namespace Ch13Ex01
{
    class Program  {
        static int counter = 0;
        static string displayString =
           "This string will appear one letter at a time. ";
        static void Main(string[] args)  {
            Timer myTimer = new Timer(100);  // 100 milliseconds
            myTimer.Elapsed += new ElapsedEventHandler(WriteChar);
            // Timer object possesses an event called Elapsed
            myTimer.Start();  // Start() is a method
            System.Threading.Thread.Sleep(200);
            ReadKey();
        }
        static void WriteChar(object source, ElapsedEventArgs e)
        {   // Program has 2 static fields: counter and displayString
            Write(displayString[counter++ % displayString.Length]);
            // var1 = var2 % var3 - var1 is the remainder when var2 divided by var3
        }
    }
}

myTimer raises a stream of events. The Timer object possesses an event called Elapsed. The event handler required by this event must match the return type and parameters of the System.Timers.ElapsedEventHandler delegate type. This is one of the standard delegates defined in the .NET Framework.

This delegate specifies the following return type and paramters:

void <MethodName>(object source, ElapsedEventArgs e);

In our code we have written a method:

static void WriteChar(object source, ElapsedEventArgs e)

The method uses two static fields of Program, counter and displayString to display a single character.

Now we need to hook this handler to an event. We need to subscribe to it. To do this use the += operator to add a handler to the event in the form of a new delegate instance initialized with your event handler method:

        static void Main(string[] args)  {
            Timer myTimer = new Timer(100);  // 100 milliseconds
            myTimer.Elapsed += new ElapsedEventHandler(WriteChar);
            // shortform of above: myTimer.Elapsed += WriteChar;

You can add as many handlers as you like to the list as long as they meet the criteria required. Each handler is called in turn when the event is raised.

Now, all you need to do is start the timer with myTimer = Start(); The result is shown below.

Ch13Ex01Events

Adding Another Handler

Let’s add another handler and add it to the list.

        // write another one here and have it subscribe
        // Write("*"); // Produces: T*h*i*s* *s*t*r*  ...
        static void WriteStar(object source, ElapsedEventArgs e)  {   
            Write("*");   
        }

To subscribe, add the following line of code below the other similar one

myTimer.Elapsed += new ElapsedEventHandler(WriteStar);

Here is the result

Ch13Ex01Events2

The next step would be to define your own events