Veteran C and C++ programmers have long used method pointers as a means to pass executable steps as parameters to another method. C# achieves the same functionality using a delegate, which encapsulates methods as objects, enabling an indirect method call bound at runtime. With a delegate, you can call a method chain via a single method object, create variables that refer to a method's chain, and use those data types as parameters to pass methods. Consider an example of where this is useful.
Defining the Scenario
Although not necessarily efficient, perhaps one of the simplest sort routines is a bubble sort. Listing 13.1 shows the BubbleSort() method.
Listing 13.1. BubbleSort() Method
This method will sort an array of integers in ascending order. However, if you wanted to support the option to sort the integers in descending order, you would have essentially two options. You could duplicate the code and replace the greater-than operator with a less-than operator. Alternatively, you could pass in an additional parameter indicating how to perform the sort, as shown in Listing 13.2.
Listing 13.2. BubbleSort() Method, Ascending or Descending
However, this handles only two of the possible sort orders. If you wanted to sort them alphabetically, randomly, or via some other mechanism, it would not take long before the number of BubbleSort() methods and corresponding SortType values would become cumbersome.
Delegate Data Types
To reduce the amount of code duplication, you can pass in the comparison method as a parameter to the BubbleSort() method. Moreover, in order to pass a method as a parameter, there needs to be a data type that can represent that methodin other words, a delegate. Listing 13.3 includes a modification to the BubbleSort() method that takes a delegate parameter. In this case, the delegate data type is GreaterThanHandler.
Listing 13.3. BubbleSort() Method with Delegate Parameter
GreaterThanHandler is a data type that represents a method for comparing two integers. Within the BubbleSort() method you then use the instance of the GreaterThanHandler, called greaterThan, inside the conditional expression. Since greaterThan represents a method, the syntax to invoke the method is identical to calling the method directly. In this case,greaterThan takes two integer parameters and returns a Boolean value that indicates whether the first integer is greater than the second one.
Perhaps more noteworthy than the particular algorithm, the GreaterThanHandler delegate is strongly typed to return a bool and to accept only two integer parameters. Just as with any other method, the call to a delegate is strongly typed, and if the data types don't match up, then the C# compiler reports an error. Let's consider how the delegate works internally.
C# defines all delegates, including GreaterThanHandler, as derived indirectly from System.Delegate, as shown in Figure 13.1.
Figure 13.1. Delegate Types Object Model
The first property is of type System.Reflection.MethodInfo, which the next chapter discusses. MethodInfo defines the signature of a particular method, including its name, parameters, and return type. In addition to MethodInfo, a delegate also needs the instance of the object containing the method to invoke. This is the purpose of the second property, Target. In the case of a static method, Target corresponds to the type itself. The purpose of the MulticastDelegate class appears later in this chapter, in the section Multicast Delegates and the Observer Pattern.
Defining a Delegate Type
You saw how to define a method that uses a delegate, and you learned how to invoke a call to the delegate simply by treating the delegate variable as a method. However, you have yet to learn how to declare a delegate data type. For example, you have not learned how to define GreaterThanHandler such that it requires two integer parameters and returns a bool.
Although all delegate data types derive indirectly from System.Delegate, the C# compiler does not allow you to define a class that derives directly or indirectly (via System.MulticastDelegate) from System.Delegate. Listing 13.4, therefore, is not valid.
Listing 13.4. System.Delegate Cannot Explicitly Be a Base Class
In its place, C# uses the delegate keyword. This keyword causes the compiler to generate a class similar to the one shown in Listing 13.4. Listing 13.5 shows the syntax for declaring a delegate data type.
Listing 13.5. Declaring a Delegate Data Type
In other words, the delegate keyword is shorthand for declaring a class derived ultimately from System.Delegate. In fact, if the delegate declaration appeared within another class, then the delegate type,GreaterThanHandler, would be a nested type (see Listing 13.6).
Listing 13.6. Declaring a Nested Delegate Data Type
In this case, the data type would be DelegateSample.GreaterThanHandler because it is defined as a nested class within DelegateSample.
Instantiating a Delegate
In this final step of implementing the BubbleSort() method with a delegate, you will learn how to call the method and pass a delegate instancespecifically, an instance of type GreaterThanHandler. To instantiate a delegate, you need a method that corresponds to the signature of the delegate type itself. In the case of GreaterThanHandler, that method takes two integers and returns a bool. The name of the method is not significant. Listing 13.7 shows the code for a greater-than method.
Listing 13.7. Declaring a GreaterThanHandler-Compatible Method
With this method defined, you can call BubbleSort() and pass the delegate instance that contains this method. With C# 2.0, you simply specify the name of the delegate method (see Listing 13.8).
Listing 13.8. Passing a Delegate Instance as a Parameter in C# 2.0
Note that the GreaterThanHandler delegate is a class, but you do necessarily use new to instantiate an instance of this class. The facility to pass the name rather than explicit instantiation is new syntax to C# 2.0. Earlier versions of the compiler require instantiation of the delegate demonstrated in Listing 13.9.
Listing 13.9. Passing a Delegate Instance as a Parameter Prior to C# 2.0
Note that C# 2.0 supports both syntaxes, but unless you are writing backward-compatible code, the 2.0 syntax is preferable.
The approach of passing the delegate to specify the sort order is significantly more flexible than the approach listed at the beginning of this chapter. With the delegate approach, you can change the sort order to be alphabetical simply by adding an alternative delegate to convert integers to strings as part of the comparison. Listing 13.10 shows a full listing that demonstrates alphabetical sorting, and Output 13.1 shows the results.
Listing 13.10. Using a Different GreaterThanHandler-Compatible Method
The alphabetic order is different from the numeric order. Note how simple it was to add this additional sort mechanism, however, compared to the process used at the beginning of the chapter.
The only changes to create the alphabetical sort order were the addition of the AlphabeticalGreaterThan method and then passing that method into the call to BubbleSort().
C# 2.0 also includes a feature known as anonymous methods. These are delegate instances with no actual method declaration. Instead, they are defined inline in the code, as shown in Listing 13.11.
Listing 13.11. Passing an Anonymous Method
In Listing 13.11, you change the call to BubbleSort() to use an anonymous method that sorts items in descending order. Notice that no LessThan() method is specified. Instead, the delegate keyword is placed directly inline with the code. In this context, the delegate keyword serves as a means of specifying a type of "delegate literal," similar to how quotes specify a string literal.
You can even call the BubbleSort() method directly, without declaring the greaterThan variable (see Listing 13.12).
Listing 13.12. Using an Anonymous Method without Declaring a Variable
Note that in all cases, the parameters and the return type must be compatible with the GreaterThanHandler data type, the delegate type of the second parameter of BubbleSort().
The anonymous method does not have any intrinsic type associated with it, although implicit conversion is possible for any delegate type as long as the parameters and return type are compatible. In other words, the anonymous method is no more a GreaterThanHandler type than another delegate type such as LessThanHandler. As a result, you cannot use the typeof() operator (Chapter 14) on an anonymous method, and calling GetType() is possible only after assigning the anonymous method to a delegate variable.
Variables that programmers declare outside an anonymous method and access within the implementation are outer variables. They are available only when using anonymous methods where they are captured such that the C# compiler takes care of passing them, along with the delegate, and returning them at the end of the invocation. In Listing 13.14, it is relatively trivial to use an outer variable to count how many times swap is called by BubbleSort(). Output 13.2 shows the results of this listing.
Listing 13.14. Using an Outer Variable in an Anonymous Method
swapCount appears outside the anonymous method and is incremented inside it. After calling the BubbleSort() method, swapCount is printed out to the console.
As this code demonstrates, the C# compiler takes care of generating CIL code that passes swapCount by reference between the anonymous method and the call site, even though there is no parameter to pass swapCount within the anonymous delegate, nor within the BubbleSort() method.