Sunday, 1 September 2013

C# Delegates Series Part 1 - Overview

At times, I have come across people who understand some basics of delegates but are really confused on when should they use delegates and how delegates are useful. During course of my development, I came across several scenarios where delegates were quite useful in achieving the desired functionality. So here is a series of delegates that would help you understand basic concepts of delegates and some scenarios  where delegates are useful.

  1. C# Delegates Series Part 1 - Overview
  2. C# Delegates Series Part 2 - Delegates allows methods to be passed as parameters
  3. C# Delegates Series Part 3 - Delegates can be used to define event handlers and event handling mechanism
  4. C# Delegates Series Part 4 - Delegates can be used to Invoke methods asynchronously


Let’s start with Overview of delegates

Delegates are similar to function pointers in C, C++. Delegates holds reference to function/method of same signature. When delegates are invoked, they in-turn invoke the function that is referenced. At first glance, it might seem difficult to understand why we need delegate and why can’t we call functions directly. Thinking of single class/file, it might not make much sense. But delegates starts getting useful when they span across multiple classes, multiple components, implementing event handles, callbacks, invoking functions asynchronously and so on. Don’t worry we would understands these scenarios in details as the article follows.

Let’s first understand steps involved in creating and using a simple delegate.

1.  Declaring delegate: A Delegate is a type that define method signature.

public delegate int MathDelegate(int a, int b);

2.  Creating method: Method that should be invoked when delegate is used.

public int Add(int a, int b)
return a + b;

public int Subtract(int num1, int num2)
return num1 - num2;

Here we define 2 methods that have same signature as delegate (return type, number of parameters and type of parameters).

Simply remove delegate keyword in step - 1 and replace MathDelegate with Add and this becomes our Add method signature.

It is not compulsory to match names of parameters. Check Subtract method where I have changed parameter name a with num1 and parameter name b with num2.

3.  Instantiate delegate: Create an instance of delegate and pass the function as parameter.

MathDelegate addDelegate = new MathDelegate(Add);
MathDelegate subtractDelegate = new MathDelegate(Subtract);

4.  Use delegate:

int result = addDelegate(10, 5);

result = subtractDelegate(10, 5);

Here, calling the delegate would invoke function that is referenced and return the result.

Now as we know what a delegate means, let’s understand some facts and real examples of delegate in next sequence of articles.

No comments:

Post a Comment