What is a Delegate?
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value.
Declaration:
public delegate returntype_of_delegate delegate_name();
Important Points:
• Delegates are similar to C++ function pointers, but are type safe.
• Delegates allow methods to be passed as parameters.
• Delegates can be used to define callback methods.
• Delegates can be chained together; for example, multiple methods can be called on a single event.
• You can use delegates without parameters or with parameter list
• You should follow the same syntax as in the method
(If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)
Basic Example:
//[a.m]delegate returntype DelegateName(Pl);
delegate int MyDel(int a, int b);
class Program
{
static void Main(string[] args)
{
SimpleMath sm = new SimpleMath();
//MyDel md1 = new MyDel(SimpleMath.Sub);
//MyDel md2 = new MyDel(sm.Add);
//MyDel md3 = md1 + md2;
MyDel md = new MyDel(SimpleMath.Sub);
md += new MyDel(SimpleMath.Add);
//Console.WriteLine(md(20,10));
Delegate[] dels = md.GetInvocationList();
foreach (Delegate item in dels)
{
Console.WriteLine();
object[] obj = { 20, 10 };
Console.WriteLine("Delegate for method {0} called; Result: {1}", item.Method.Name, item.Method.Invoke(null, obj));
}
Console.ReadLine();
}
}
class SimpleMath
{
public static int Add(int num1, int num2)
{
return num1 + num2;
}
public static int Sub(int num1, int num2)
{
return num1 - num2;
}
}
Output:
Delegate for method Sub called; Result: 10
Delegate for method Add called; Result: 30
Example Combine Delegates:
delegate void Del(string s);
class TestClass
{
static void Hello(string s)
{
System.Console.WriteLine(" Hello, {0}!", s);
}
static void Goodbye(string s)
{
System.Console.WriteLine(" Goodbye, {0}!", s);
}
static void Main()
{
Del a, b, c, d;
// Create the delegate object a that references
// the method Hello:
a = Hello;
// Create the delegate object b that references
// the method Goodbye:
b = Goodbye;
// The two delegates, a and b, are composed to form c:
c = a + b;
// Remove a from the composed delegate, leaving d,
// which calls only the method Goodbye:
d = c - a;
System.Console.WriteLine("Invoking delegate a:");
a("A");
System.Console.WriteLine("Invoking delegate b:");
b("B");
System.Console.WriteLine("Invoking delegate c:");
c("C");
System.Console.WriteLine("Invoking delegate d:");
d("D");
}
}
Output:
Invoking delegate a:
Hello, A!
Invoking delegate b:
Goodbye, B!
Invoking delegate c:
Hello, C!
Goodbye, C!
Invoking delegate d:
Goodbye, D!