Can anybody explain to me why we need delegates and what are the advantages of them?
Here is a simple program I have created with and without delegates (using plain methods):
Program with without delegates:
namespace Delegates
{
class Program
{
static void Main(string[] args)
{
abc obj = new abc();
int a = obj.ss1(1, 2);
int b = obj.ss(3,4);
Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);
Console.ReadKey();
}
}
class abc
{
public int ss(int i, int j)
{
return i * j;
}
public int ss1(int x, int y)
{
return x + y;
}
}
}
Program with Delegates:
namespace Delegates
{
public delegate int my_delegate(int a, int b);
class Program
{
static void Main(string[] args)
{
my_delegate del = new my_delegate(abc.ss);
abc obj = new abc();
my_delegate del1 = new my_delegate(obj.ss1);
int a = del(4, 2);
int b = del1(4, 2);
Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);
Console.ReadKey();
}
}
class abc
{
public int ss(int i, int j)
{
return i * j;
}
public int ss1(int x, int y)
{
return x + y;
}
}
}
Both programs give the same results, so what is advantage of using Delegates
?
Thanks.