csharp_delegates
csharp_delegates
C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference type variable that holds the
reference to a method. The reference can be changed at runtime.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived
from the System.Delegate class.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method,
which have the same signature as that of the delegate.
The preceding delegate can be used to reference any method that has a single string parameter and returns an int type
variable.
Instantiating Delegates
Once a delegate type has been declared, a delegate object must be created with the new keyword and be associated with
a particular method. When creating a delegate, the argument passed to the new expression is written like a method call,
but without the arguments to the method. For example:
Following example demonstrates declaration, instantiation and use of a delegate that can be used to reference methods
that take an integer parameter and returns an integer value.
using System;
When the above code is compiled and executed, it produces following result:
Value of Num: 35
Value of Num: 175
Multicasting of a Delegate
Delegate objects can be composed using the "+" operator. A composed delegate calls the two delegates it was composed
from. Only delegates of the same type can be composed. The "-" operator can be used to remove a component delegate
from a composed delegate.
Using this useful property of delegates you can create an invocation list of methods that will be called when a delegate is
invoked. This is called multicasting of a delegate. The following program demonstrates multicasting of a delegate:
using System;
When the above code is compiled and executed, it produces following result:
Value of Num: 75
Use of Delegate
The following example demonstrates the use of delegate. The delegate printString can be used to reference methods that
take a string as input and return nothing.
We use this delegate to call two methods, the first prints the string to the console, and the second one prints it to a file:
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
When the above code is compiled and executed, it produces following result: