Delegates and Events in C#

Delegate Declaration and Instantiation

Delegates can be specified on their own in a namespace, or else can be specified within another class (the examples below all show the latter). In each case, the declaration specifies a new class, which inherits from System.MulticastDelegate.

Each delegate is limited to referencing methods of a particular kind only. The type is indicated by the delegate declaration – the input parameters and return type given in the delegate declaration must be shared by the methods its delegate instances reference. To illustrate this: a delegate specified as below can be used to refer only to methods which have a single String input and no return value:

public delegate void Print (String s);

Suppose, for instance, that a class contains the following method:

public void realMethod(string myString)
{
                // method code
}

Another method in this class could then instantiate the ‘Print’ delegate in the following way, so that it holds a reference to ‘realMethod’:

Print delegateVariable = new Print(realMethod);

We can note two important points about this example. Firstly, the unqualified method passed to the delegate constructor is implicitly recognised as a method of the instance passing it. That is, the code is equivalent to:

Print delegateVariable = new Print(this.realMethod);

We can, however, in the same way pass to the delegate constructor the methods of other class instances, or even static class methods. In the case of the former, the instance must exist at the time the method reference is passed. In the case of the latter (exemplified below), the class need never be instantiated.

Print delegateVariable = new Print(ExampleClass.exampleMethod);

The second thing to note about the example is that all delegates can be constructed in this fashion, to create a delegate instance which refers to a single method. However, as we noted before, some delegates – termed ‘multicast delegates’ – can simultaneously reference multiple methods. These delegates must – like our Print delegate – specify a ‘void’ return type.

One manipulates the references of multicast delegates by using addition and subtraction operators (although delegates are in fact immutable reference types). The following code gives some examples:

Print s = null;
s = s + new Print(realMethod);
s += new Print(realMetohod);

The – and -= operators are used in the same way to remove method references from a delegate.

The following code gives an example of the use of delegates. In the Main method, the Print delegate is instantiated twice, taking different methods. These Print delegates are then passed to the Display method, which by invoking the Print delegate causes the method it holds to run. As an exercise, you could try rewriting the code to make Print a multicast delegate.

using System;
using System.IO;

public class DelegateTest
(
     public delegate void Print (String s);
 
     public static void Main()
     {
         Print s = new Print (toConsole);
         Print v = new Print (toFile);

         Display (s);
         Display (v);
     }

     public static void toConsole (String str)
     {
         Console.WriteLine(str);
     }

     public static void toFile (String s)
     {
         StreamWriter fileOut = File.CreateText(“fred.txt”);
         fileOut.WriteLine(s);
         fileOut.Flush();
         fileOut.Close();
     }

     public static void Display(Print pMethod)
     {
         pMethod(“This should be displayed in the console”);
     }
 }
 

Events

 

To recap: in object-oriented languages, objects expose encapsulated functions called methods. Methods are encapsulated functions which run when they are invoked.

Sometimes, however, we think of the process of method invocation more grandly. In such a case, the method invocation is termed an ‘event’, and the running of the method is the ‘handling’ of the event. An archetypal example of an event is a user’s selection of a button on a graphical user interface; this action may trigger a number of methods to ‘handle’ it.

What distinguishes events from other method invocations is not, however, that they must be generated externally. Any internal change in the state of a program can be used as an event. Rather, what distinguishes events is that they are backed by a particular ‘subscription-notification’ model. An arbitrary class must be able to ‘subscribe to’ (or declare its interest in) a particular event, and then receive a ‘notification’ (ie. have one of its methods run) whenever the event occurs.

Delegates – in particular multicast delegates – are essential in realizing this subscription-notification model. The following example describes how Class 2 subscribes to an event issued by Class 1.

1. Class 1 is an issuer of E-events. It maintains a public multicast delegate D.

2. Class 2 wants to respond to E-events with its event-handling method M. It therefore adds onto D a reference to M.

3. When Class 1 wants to issue an E-event, it calls D. This invokes all of the methods which have subscribed to the event, including M.

The ‘event’ keyword is used to declare a particular multicast delegate (in fact, it is usual in the literature to just identify the event with this delegate). The code below shows a class EventIssuer, which maintains an event field myEvent. We could instead have declared the event to be a property instead of a field . To raise the myEvent event, the method onMyEvent is called (note that we are checking in this method to see if myEvent is null – trying to trigger a null event gives a run-time error).

public class EventIssuer
{
     public delegate void EventDelegate(object from, EventArgs args);

     public event EventDelegate myEvent;

     protected virtual void onMyEvent(EventArgs args)
     {
         if (myEvent!=null)
  {
             myEvent(this,
  }
     }
}

A class which wanted to handle the events issued by an EventIssuer ei with its method handleEvents would then subscribe to these events with the code:

ei.myEvent += new EventIssuer.EventDelegate(handleEvents);

Good Practice For Events

The code above demonstrates some points about event-handling which are not enforced by the language architecture, but are used throughout the .Net framework as good practice.

1. When you want to raise an event in code, you don’t tend to trigger the class’s event object directly. Rather, you call a ‘protected, virtual’ method to trigger it (cf. the onMyEvent method above).

2. By convention, when events are raised they pass two objects to their subscribers. The first is a reference to the class raising the event; the second is an instance of the System.EventArgs class which contains any arbitrary data about the event.

3. If an event is not interested in passing data to subscribers, then its defining delegate will still reference an EventArgs object (but a null value will be passed by the event). If an event should pass data to its subscribers, however, then it is standard to use a specific class which derives from the EventArgs class to hold this data.

4. When you write a class which inherits from an event-raising base class, you can ‘intercept’ an event by overriding the method used to raise it. The following code illustrates such an intercept – classes which subscribe to the event will never receive notifications about it.

protected override void onMyEvent(EventArgs args)
{
     Console.WriteLine(“hello”);
}

If you want subscribers to continue to receive notifications despite such an ‘intercepting’ method, however, then you can call the base class method as in the following:

protected override void onMyEvent(EventArgs args)
{
     Console.WriteLine(“hello”);
     base.onMyEvent(args);
}

Advertisements

About Saad Khan

Saad is an ASP.NET developer with 4 years of experience, and has also made a number of contributions to the Sitefinity marketplace and community. He loves to explore new code, and create innovative tools and procedures while exploring new approaches in his work with Sitefinity and MVC. As an experienced .NET developer, he frequents both Telerik and Microsoft technologies. In his spare time, Saad is an avid gamer and movie fanatic, and also experiments with new and interesting tools on the Microsoft platform.​​

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: