Delegates are a feature of
C# that implement functionality similar to
function pointers in
C and
C++. Unlike function pointers, delegates are a fully
object oriented solution to the problem.
Syntax
To create a delegate, a delegate
type is defined using the delegate
keyword. The definition looks a lot like a
method declaration, but really it is closer to a
class definition, as you're really defining a new type. For example:
public delegate void my_delegate(string message);
This defines a new delegate type named "my_delegate" which points at a method with one string argument and which returns nothing (void). This type can then be instantiated using the standard new operator, giving the method for the delegate to point at as an argument.
Full Example
using System;
class Foo {
public void my_method(string message) {
Console.WriteLine("my_method: " + message);
}
public delegate void my_delegate(string message);
public static void Main(string args) {
Foo my_obj = new Foo();
my_delegate foo = new my_delegate(my_obj.my_method);
foo("hello");
}
}
This creates a new
object of the Foo class, and then creates a delegate to point at the my_method method of this object. The method can then be invoked through the delegate using the standard method/function syntax.
Conclusion
As well as object methods, delegates can also be made to point at
static class methods. The compiler only cares that the arguments and return type are the same.
Of course, delegates are pretty much obsolete in any language which has a lambda construct such as Lisp or Ruby.