A
delegate is a type that safely encapsulates a method, similar to a
function pointer in
C and
C++. Unlike C function pointers, delegates are
object-oriented,
type safe, and
secure. The type of a delegate is defined by the
name of the delegate.
An small example:
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
}
And now declare and just call..
Del handler = DelegateMethod;
handler("Hello World");
Some scopes where delegates are used:
1. Event handlers (for GUI and more)
2. Starting threads
3. Callbacks (e.g. for async APIs)
4. LINQ and similar (List.Find etc)
5. Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)
Some live examples you can view here:
The Power of Delegates in C#[
^]
C# - Delegates 101 - A Practical Example[
^]
http://stackoverflow.com/questions/2019402/when-why-to-use-delegates[
^]