- C# Delegates Introduction
- C# Delegates Part 2
- C# Delegates Part 3
- C# Delegates Part 4
- C# Delegates General
- C# Delegates Steps
- C# Delegates Illustrated Example
- C# Delegates Anonymous Methods
The book Illustrated C# 7, Fifth Edition by Daniel Solis and Cal Schrotenboer published by Apress there is an example of a delegate on page 360.
- Class Test defines two print functions.
- Method Main creates an instance of the delegate and then adds three more methods with +=.
- The program then invokes the delegate, which calls its methods. Before invoking the delegate, however, it checks to make sure
it’s not null. - You can remove any method from the invocation list with -=.
- You can use either static methods or instance methods to instantiate a delegate.
Below is the example code, modified by including a removal of one of the methods.
using System; namespace IllustratedPage360 { // Define a delegate type with no return value and no parameters. delegate void PrintFunction(); class Test { public void Print1() { Console.WriteLine("Print1 -- instance"); } public static void Print2() { Console.WriteLine("Print2 -- static"); } } class Program { static void Main(string[] args) { Test t = new Test(); // Create a test class instance. PrintFunction pf; // Create a null delegate. pf = t.Print1; // Instantiate and initialize the delegate. // Add three more methods to the delegate. pf += Test.Print2; pf += t.Print1; pf += Test.Print2; pf -= t.Print1; // remove method even though it was not last one // The delegate now contains four methods. if (null != pf) // Make sure the delegate isn't null. pf(); // Invoke the delegate. else Console.WriteLine("Delegate is empty"); } } // OUTPUT: // Print1 -- instance // Print2 -- static // Print1 -- instance // This one was removed above and will not display! // Print2 -- static }