Delegates similar to NotifyEvents or procedures of object in Delphi,
We can register or unregister handlers in calling code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Delegates { class Program { static void Main(string[] args) { SomeClass sc = new SomeClass(); sc.RegisterHandler(new SomeClass.SomeDelegate(DelegateHandler)); sc.RegisterHandler(new SomeClass.SomeDelegate(DelegateHandler2)); sc.UnRegisterHandler(new SomeClass.SomeDelegate(DelegateHandler2)); sc.SomeMethod(); // will fire list of handlers Console.ReadLine(); } public static void DelegateHandler(string Amessage) { Console.WriteLine("Delegate handler message="+Amessage); } public static void DelegateHandler2(string Amessage) { Console.WriteLine("Another handler message = "+Amessage); } } class SomeClass { // delegate block public delegate void SomeDelegate(string Amessage); private SomeDelegate listOfHandlers; public void RegisterHandler(SomeDelegate method) {listOfHandlers += method;} public void UnRegisterHandler(SomeDelegate method) { listOfHandlers -= method; } //do something in class public void SomeMethod() { //some code if (listOfHandlers != null) { listOfHandlers("hello from delegate method"); } //some code } } } |