Why and Where to use Delegate in C#

Posted on Posted in C#, Microsoft

I am going to explain why and where we need to use delegates in C#.

Let’s suppose we have an investment application, which takes investment from customers and then calculates profit on the basis of investment.

We have some rules

1) If investment is less than 10000 then we want to give profit to customer > investment*2

2) If investment is more than 10000 then we want to give profit to customer >  investment*3

What we could do is define methos, then calculate on the basis of investment etc. but it’s going to get complicated when it grows and will end up with loads of code in one method…

Here it comes a delegate……

Let’s define two methods

1) to make profit double

2) to make profit tripple

two methods

above two methods will give us calculations

Now let’s create a delegate

delegate

We want to create a generic method which will give us details about the profit of a customer on the basis of investment.

method generic

First parameter is int i.e. investment amount, second parameter is of type our delegate – why??? because we dont know what type of calculation we are going to pass so we have defined a delegate and we will pass that to get our results

this parameter can be any method of ExecuteMethodDelegate type and it will depend on investment amount which is below

main method

Now if you look at the code above you will see we are calling our generic method i.e. ExecuteMethod and passing it investment amount and a delegate – delegate differs on the basis of investment amount and parameter (delegate) performs its calculations and pass it our generic method.

We can extend this and declare and pass any other methods of this type which will return a calculation and then use it.

Hope this helps.

 

Full code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdvancedCSharp.Delegates
{
public delegate int ExecuteMethodDelegate(int number);
public class Program
{
static void Main(string[] args)
{
int investment;
//if investment is less than 10000 then investment *2 else investment *3
investment = 9000;

ExecuteMethodDelegate exe = MakeDouble;
if (investment <10000)
{
ExecuteMethod(investment, exe);
}
else
{
exe = MakeTripple;
ExecuteMethod(investment, exe);
}
}

public static int MakeDouble(int num)
{
return 2*num;
}
public static int MakeTripple(int num)
{
return 3 * num;
}

///
/// general execute mthod which gets called on addition, deletion etc.
///

public static void ExecuteMethod(int num, ExecuteMethodDelegate del)
{
Console.WriteLine(“START”);

var value = del(num);
Console.WriteLine(“You will get: ” + value);

Console.WriteLine(“END”);

}
}

}