Table of contents Home page
using System; public delegate void MyDelegate(int n); public class Program { private static void method1(int n) { Console.WriteLine("Value {0} passed to method1", n); } private static void method2(int n) { Console.WriteLine("Value {0} passed to method2", n); } public static void Main() { Program.method1(1); // Direct call to method1 MyDelegate md = new MyDelegate(Program.method1); md(2); // Indirect call to method1 md = Program.method2; md(3); // Indirect call to method2 Console.ReadKey(); } }
using System; public delegate void MulticastDelegate(int n); public class Program { private static void method1(int n) { Console.WriteLine("Value {0} passed to method1", n); } private static void method2(int n) { Console.WriteLine("Value {0} passed to method2", n); } public static void Main() { MulticastDelegate md = new MulticastDelegate(Program.method1); md += new MulticastDelegate(Program.method2); md(1); // Call method1 and method2 Console.WriteLine(); md -= new MulticastDelegate(Program.method1); md(2); // Call method2 Console.ReadKey(); } }
using System; public delegate void ButtonEventHandler(); // Define the signature of the event handler public class Button { public event ButtonEventHandler buttonClick; // Associate the event with the delegate public void simulatedClick() { Console.WriteLine("click"); if (buttonClick != null) { buttonClick(); } } } public class Program { public static void Main() { Button b = new Button(); b.buttonClick += new ButtonEventHandler(onClick); // Subscribe to the ButtonClick event b.simulatedClick(); // Raise the event Console.ReadKey(); } // Event handler public static void onClick() { Console.WriteLine("Event handler executing"); } }