C# Delegates Illustrated Example


This entry is part 7 of 8 in the series C# Delegates

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.

1using System;
2 
3namespace IllustratedPage360
4{
5    // Define a delegate type with no return value and no parameters.
6    delegate void PrintFunction();
7 
8    class Test
9    {
10        public void Print1()
11           { Console.WriteLine("Print1 -- instance"); }
12        public static void Print2()
13           { Console.WriteLine("Print2 -- static"); }
14    }
15    class Program
16    {
17        static void Main(string[] args)
18        {
19            Test t = new Test(); // Create a test class instance.
20            PrintFunction pf; // Create a null delegate.
21            pf = t.Print1; // Instantiate and initialize the delegate.
22                           // Add three more methods to the delegate.
23            pf += Test.Print2;
24            pf += t.Print1;
25            pf += Test.Print2;
26            pf -= t.Print1;  // remove method even though it was not last one
27            // The delegate now contains four methods.
28            if (null != pf) // Make sure the delegate isn't null.
29                pf(); // Invoke the delegate.
30            else
31                Console.WriteLine("Delegate is empty");
32        }
33    }
34    // OUTPUT:
35    // Print1 -- instance
36    // Print2 -- static
37    // Print1 -- instance // This one was removed above and will not display!
38    // Print2 -- static
39}
Series Navigation<< C# Delegates StepsC# Delegates Anonymous Methods >>