C# delegation
A Delegate in C# is similar to a pointer to a function in C or C++. A Delegate is a reference type variable that holds a reference to a method. References can be changed at run time.
Delegate is especially used to implement events and callback methods. All Delegate are derived from System.Delegate
class.
Declare delegation
The delegate declaration determines the methods that can be referenced by the delegate. A delegate can point to a method that has the same label as it.
For example, suppose you have a delegate:
public delegate int MyDelegate (string s);
The above delegate can be used to reference any one with a single string
parameter and returns a int
type variable.
The syntax for declaring a delegate is as follows:
delegate <return type> <delegate-name> <parameter list>
Instantiate delegate
Once the delegate type is declared, the delegate object must use the new
keyword, and is related to a specific method. When you create a delegate, pass it to the new
arguments of the statement are writtenas if they were method calls, but without arguments. For example:
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
The following example demonstrates the declaration, instantiation, and use of a delegate, which can be used to reference a method with an integer parameter and return an integer value.
Example
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 Instance
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
// Calling methods using delegate objects
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
Value of Num: 35
Value of Num: 175
Multicasting of a Delegate
The delegate object can use the +
operator to merge. A merge delegate invokes the two delegates it merges. Only delegates of the same type can be merged. -
operators can be used to remove component delegates from merged delegates.
Using this useful feature of a delegate, you can create a call list of methods to be called when the delegate is called. This is called delegated multicasting, also known as multicast. The following program demonstrates multicast of a delegate:
Example
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 Instance
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
// Call Multicast
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
Value of Num: 75
Purpose of delegation
The following example demonstrates the use of delegates. Entrust printString
can be used to reference a method with a string as input anddoes not return anything.
We use this delegate to call two methods, the first to print the string to the console and the second to print the string to the file:
Example
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// declaration of trust
public delegate void printString(string s);
// This method prints to the console
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
// This method prints to a file
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\\\message.txt", FileMode.Append,
FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// This method takes a delegate as a parameter and uses it to call the method
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following results:
The String is: Hello World