Understanding Delegates in C#

Basically it is similar like the old “C” age function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions. C# delegate is the smarter version of function pointer which helps software architects a lot, specially while utilizing design patterns.

At first, a delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function. The function will then can be called via the delegate object.

Sounds easy? If not lets have a look in the code snippets below.

1. Defining the delegate

public delegate int Calculate (int value1, int value2);

2. Creating methods which will be assigned to delegate object

//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate
public int add(int value1, int value2)
{
return value1 + value2;
}
//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate
public int sub( int value1, int value2)
{
return value1 - value2;
}

3. Creating the delegate object and assigning methods to those delegate objects

//creating the class which contains the methods
//that will be assigned to delegate objects
MyClass mc = new MyClass();
//creating delegate objects and assigning appropriate methods
 //having the EXACT signature of the delegate
 Calculate add = new Calculate(mc.add);
 Calculate sub = new Calculate(mc.sub);
 

4. Calling the methods via delegate objects

//using the delegate objects to call the assigned methods
Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));

Benefis
They’re a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn’t need to know what it does, just how to call it at the right time.
Another example is LINQ – filtering, projecting etc all require the same kind of template code; all that changes is the logic to represent the filter, the projection etc. With lambda expressions in C# 3 (which are converted into delegates or expression trees) this makes it really simple:

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...