// What is the advantage of Delegates public static void DelegatesDemo() { // A very good example https://buildplease.com/pages/why-delegates/ //1. A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. //2. Delegates are mainly used in implementing the call-back methods and events. //3. Delegates can also be used in “anonymous methods” invocation. //4. A delegate will call only a method which agrees with its signature and return type. // A method can be a static method associated with a class or can be an instance method associated with an object, it doesn’t matter. //5. Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). // It helps the user to point more than one method in a single call. // Delegates are combined and when you call a delegate then a complete list of methods is called. // All methods are called in First in First Out(FIFO) order. // ‘+’ or ‘+=’ Operator is used to add the methods to delegates. // ‘–’ or ‘-=’ Operator is used to remove the methods from the delegates list. // multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception. // Also, the multicasting of delegate will return the value only from the last method added in the multicast. Although, the other methods will be executed successfully. //Good example //You're an O/S, and I'm an application.I want to tell you to call one of my methods when you detect something happening. //To do that, I pass you a delegate to the method of mine which I want you to call. //I don't call that method of mine myself, because I want you to call it when you detect the something. //You don't call my method directly because you don't know (at your compile-time) that the method exists (I wasn't even written when you were built); //instead, you call whichever method is specified by the delegate which you receive at run - time. LongRunningTask longRunningTask = new LongRunningTask(); longRunningTask.Start(new CallbackDelegate(MyCallbackMthod)); }
private static void MyCallbackMthod(LongRunningTask t, TaskStatus status) { Console.WriteLine("The task status is {0}", status); }