Home Programming Guide What are, Why, When and How we use Delegates in C#?

What are, Why, When and How we use Delegates in C#?

31
0

What are Delegates?

A Delegate is a reference type variable that can hold a reference to the method(s) with a particular parameter list and return type. The reference can be changed at runtime.

Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. All delegates are implicitly derived from the System.Delegate class.

If you want to invoke or call a method using delegates then you need to follow three simple steps.  The steps are as follows.

  1. Defining a delegate
  2. Instantiating a delegate
  3. Invoking a delegate

Syntax :

[access_modifier] delegate [return_type] [delegate_name] ([parameter_list]);

Example :

public delegate int Add (int number1,int number2);
// public is access_modifier
// int is return type.
// Add is delegate_name.
// number1, number2 are parameters.

Why we use it Delegates?

Delegate is used for designing extensible and flexible applications ( or design the framework). You can point any methods in the application through the delegate instance, which match the signature of the delegate.

For E.g :

There are 100 functions. The user is asked to enter a number between 1–100. If he enters 1, function1 is executed. if he enters 2, function2 is executed. How would you code it? Write a series of if..then or switch..case statements. C programmers can easily solve it by creating an array[0..99], storing the 100 function pointers, and invoking the functions by accessing the array elements.

How would you do it in C#? use an array to store the delegates – delegates are nothing but function pointers plus a lot more. That lot more gives a programmer more power and tools to do things with delegates but explaining those would outside this question topic.

When we use Delegates?

A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructors, or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that’s when you’ll need delegates.

How we can use Delegates?

There are three types of delegates in c#:

  1. Single Delegate.
    2. Multicast Delegate.
    3. Generic Delegate.

Single Delegate

using System;
public class Program
{
// Declare a delegate
delegate double CalculateSimpleInterest(double p, double t, double r);
static CalculateSimpleInterest simpleInterest = getTotalInterest;

static void Main(string[] args)
{
double totalInterest;
//Funtion I : Invocation of simple delegate by using Invoke keyword
totalInterest = simpleInterest.Invoke(200, 1, 3.25);
Console.WriteLine("Total Interest of $200 in a year at rate of 3.25% AUG is {0}",totalInterest);

//Funtion II : Invocation of simple delegate by passing method name
CalculateSimpleInterest D = new CalculateSimpleInterest(getTotalInterest);
totalInterest = D(200, 1, 3.25);
Console.WriteLine("Total Interest of $200 in a year at rate of 3.25% AUG is {0}", totalInterest);
Console.ReadKey();
}
//Creating methods which will be assigned to delegate object
/// <summary>
/// Gets the total interest.
/// </summary>
/// <param name="p" />The Principal.
/// <param name="t" />The Time.
/// <param name="r" />The Rate.
/// <returns>Total Interest
static double getTotalInterest(double p, double t, double r)
{
return (p * t * r) / 100;
}
}

Multicast Delegate

using System;
public class Program
{
// Declare a delegate
delegate double CalculateSimpleInterest(double para1, double para2, double para3);
static CalculateSimpleInterest simpleInterest = getTotalInterest;

static void Main(string[] args)
{
double si;
//Calculating simple interest
si = simpleInterest.Invoke(120, 1, 3.25);
//using multicast delegate by invoking method getInterestRatePerYear()
simpleInterest += new CalculateSimpleInterest(getInterestRatePerYear);
double Rate=simpleInterest.Invoke(si, 120, 1);
Console.WriteLine("The AUG rate is {0}", Rate);
//using multicast delegate by invoking method getInterestTimeSpan()
simpleInterest += new CalculateSimpleInterest(getInterestTimeSpan);
double TimeSpan = simpleInterest.Invoke(si, 120, 3.25);
Console.WriteLine("The Time Span is {0}", TimeSpan);

Console.ReadKey();
}
/// <summary>
/// Gets the total interest.
/// </summary>
/// <param name="p" />The Principal.
/// <param name="t" />The Time.
/// <param name="r" />The Rate.
/// <returns>Total Interest
static double getTotalInterest(double p, double t, double r)
{
return (p * t * r) / 100;
}
/// <summary>
/// Gets the interest rate per year.
/// </summary>
/// <param name="si" />The Simple Interest.
/// <param name="p" />The Principal.
/// <param name="t" />The Time.
/// <returns>Interest rate per year
static double getInterestRatePerYear(double si, double p, double t)
{
return (si * 100)/(p*t);
}
/// <summary>
/// Gets the interest time span.
/// </summary>
/// <param name="si" />The Simple Interest.
/// <param name="p" />The Principal.
/// <param name="r" />The Rate.
/// <returns>Interest time span
static double getInterestTimeSpan(double si, double p, double r)
{
return (si * 100) / (p * r);
}
}

Generic Delegates

There are three types of generic delegates in c#:

  1. Func Generic Delegate.
    2. Action Generic Delegate.
    3. Predicate Generic Delegate.