Wednesday 11 September 2013

A short introduction to delegates in C#

Imagine that you have some code that iterates over a list of ints and prints them.

Now, suppose that you decide that you want your display method to display them in a different way.  You actually want to write your list to a file rather than printing to the console, but you need to be backwards-compatible, so you need to retain the ability to simply print to console.

The first thing that you think of might be to create some sort of Handler object and call the equivalent of the handler.handle() method on it (this is essentially the strategy pattern, if you are interested). This is shown in the following example:

We have classes implementing the IDisplayHandler interface which display objects in different ways.

Example usage is shown below:

Lovely, you say.  Where on earth do delegates come into this?  Well, in C# you can use delegates to do make this solution much simpler.

Introduction to Delegates


Essentially, a delegate is a type which defines a method signature. An instance of a delegate can point to any method with the corresponding signature and delegates are used to pass around methods as parameters.

For example:

public delegate int ExecuteCalculation(int x, int y); 

This defines a method signature which takes in two ints and returns one int. Let's understand this more clearly with a simple example based on our strategy pattern display example above.

Simple Delegate Example


Define a delegate using the delegate keyword.

 private delegate void DisplayIt(object o); 

This delegate will need to point to a method which takes in any object and returns void.

I know a method like this! The plain old Console.WriteLine().

var display = new DisplayIt(Console.WriteLine());

All that remains is to pass it into the Display method which, instead of calling Console.Writeline() explicitly will simply pass the objects to the delegate which in turn calls its 'Invoke' method and VOILA, you have printed to the console.  

The example below shows the complete code:






No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...