C# delegates are similar to pointers to functions, in C or C++. The delegates are used to perform tasks associated with a function while that function is invoked delegate will perform the task.
For example, Lets take a delegate:
public delegate int the firstDelegate (string s);
The preceding delegate can be used to invoke when any function with int return type and string parameter is invoked
Syntax for delegate declaration is:
delegate <return type> <delegate-name> <parameter list>
Implementing a Delegate :
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
//calling the methods using the delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
This delegates are called single cast delegates
Multicast Delegate
Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. It shows the binding of the function with the delegate. Composed delegate calls two delegates from which it was composed. To remove a component delegate from a composed delegate "-" operator is used in multicast delegate.
using System;
delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}
public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}
static void Main(string[] args)
{
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
//calling multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
0 Comment(s)