About
In this code snippet, we will take a look at delagates in C#.
A delegate is a pointer to a method(basically an indirect call to the method). Delegates can be passed as input parameters to other methods. A benefit of this is that it provides flexibility. Such a method can then use the passed in delegate to call another method(callback method). This is actually the way events work in .NET.
Let’s have a look at the code below to see how to use delegates.
Code:
using System;
namespace Delegates
{
class Program
{
static void Main(string[] args)
{
//A delegate is a pointer to a method. Basically an indirect call to the method.
//The benefit of not calling a function directly but using a delegate to do so is flexibility.
//For example:
//Example 1/////////////////////////////////////
//The delegate instance now points to myMethod. But it could point to any method with the same signiture.
myDelegateMethod myDelegate = new myDelegateMethod(myMethod);
//But why use a delegate like so ...
myDelegate("Hi.");
//... insetad of just calling the method like this.
myMethod("Hi.");
////////////////////////////////////////////////
//Example 2/////////////////////////////////////
//Here is an example of when it makes sense to use a delegate.
Operation op = new Operation(add);
//We can just pass a reference to the method that we want to invoke.
calculateSomething(10, 5, op);
op = new Operation(subtract);
calculateSomething(10, 5, op);
///////////////////////////////////////////////
Console.ReadLine();
}
//Example 1/////////////////////////////////////////
public delegate void myDelegateMethod(string inputText);
public static void myMethod(string inputText)
{
Console.WriteLine(inputText);
}
////////////////////////////////////////////////////
//Example 2////////////////////////////////////////
public static void calculateSomething(double a, double b, Operation op)
{
double result = op(a, b);
//Do some calculating.
// ...
Console.WriteLine("Result: " + result);
}
//Delegate declaration.
public delegate double Operation(double a, double b);
//The following methods all have the same signiture(input parameters). Consequently they can all be delegated by the "Operation" delegate.
public static double add(double a, double b)
{
return a + b;
}
public static double subtract(double a, double b)
{
return a - b;
}
public static double multiply(double a, double b)
{
return a * b;
}
public static double divide(double a, double b)
{
return a / b;
}
///////////////////////////////////////////////////
}
}





