Code to declare a delegate type, named SendMessageDelegate, which takes a Message as a parameter and returns void: delegate void SendMessageDelegate(Message message); Code to define a method that takes an instantiated delegate as its argument: void SendMessage(SendMessageDelegate sendMessageDelegateReference) { // Call the delegate and any other chained delegates synchronously. sendMessageDelegateReference(new Message("hello this is a sample message")); } The implemented method that runs when the delegate is called: void HandleSendMessage(Message message) { // The implementation for the Sender and Message classes are not relevant to this example. Sender.Send(message); } Code to call the SendMessage method, passing an instantiated delegate as an argument: SendMessage(new SendMessageDelegate(HandleSendMessage));
Delegates (C#) delegate void Notifier(string sender); // Normal method signature with the keyword delegate Notifier greetMe; // Delegate variable void HowAreYou(string sender) { Console.WriteLine("How are you, " + sender + '?'); } greetMe = new Notifier(HowAreYou); A delegate variable calls the associated method and is called as follows: greetMe("Anton"); // Calls HowAreYou("Anton") and prints "How are you, Anton?" Delegate variables are
first-class objects of the form and can be assigned to any matching method, or to the value . They store a method and its receiver without any parameters: new DelegateType(funnyObj.HowAreYou); The object can be and omitted. If the method is , it should not be the object (also called an instance in other languages), but the class itself. It should not be , but could be , or . To call a method with a delegate successfully, the method signature has to match the with the same number of parameters of the same kind (, , ) with the same type (including return type).
Multicast delegates (C#) A delegate variable can hold multiple values at the same time: void HowAreYou(string sender) { Console.WriteLine($"How are you, {sender}?"); } void HowAreYouToday(string sender) { Console.WriteLine($"How are you today, {sender}?"); } Notifier greetMe; greetMe = HowAreYou; greetMe += HowAreYouToday; greetMe("Leonardo"); // "How are you, Leonardo?" // "How are you today, Leonardo?" greetMe -= HowAreYou; greetMe("Pereira"); // "How are you today, Pereira?" If the multicast delegate is a function or has no parameter, the parameter of the last call is returned. == Technical implementation details ==