A delegate declaration defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.
The delegate declaration takes the form:
[attributes] [modifiers] delegate result-type identifier ([formal-parameters]);
where:
For more information on delegates, see §15 in the language reference.
In the following example, one delegate is mapped to both static and instance methods and returns specific information from each.
// Calling both static and instance methods from delegates using System; delegate int MyDelegate(); // delegate declaration public class MyClass { public int InstanceMethod () { Console.WriteLine("A message from the instance method."); return 0; } static public int StaticMethod () { Console.WriteLine("A message from the static method."); return 0; } } public class MainClass { static public void Main () { MyClass p = new MyClass(); // Map the delegate to the instance method: MyDelegate d = new MyDelegate(p.InstanceMethod); // Call the instance method: d(); // Map to the static method: d = new MyDelegate(MyClass.StaticMethod); // Call the static method: d(); } }
A message from the instance method. A message from the static method.