Method Pointers


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

 class SimpleSort {   public static void BubbleSort(int[] items)   {      int i;      int j;      int temp;        for (i = items.Length - 1; i >= 0; i--)      {          for (j = 1; j <= i; j++)          {              if (items[j - 1] > items[j])              {                  temp = items[j - 1];                  items[j - 1] = items[j];                  items[j] = temp;              }          }      }   }   // ... }    

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

 class SimpleSort {  ...  public enum SortType  {      Ascending,      Descending  }  public static void BubbleSort(int[] items, SortType sortOrder)                 {      int i;      int j;      int temp;         for (i = items.Length - 1; i >= 0; i--)      {          for (j = 1; j <= i; j++)          {              switch (sortOrder)              {                  case SortType.Ascending :                                                        if (items[j - 1] > items[j])                                                   {                          temp = items[j - 1];                          items[j - 1] = items[j];                          items[j] = temp;                      }                      break;                  case SortType.Descending :                                                       if (items[j - 1] < items[j])                                                   {                          temp = items[j - 1];                        items[j - 1] = items[j];                        items[j] = temp;                      }                      break;                }             }          }       }       ...    } 

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

 class DelegateSample {     // ...     public static void BubbleSort(                                                  int[] items, GreaterThanHandler greaterThan)                            {         int i;         int j;         int temp;         for (i = items.Length - 1; i >= 0; i--)         {             for (j = 1; j <= i; j++)             {                 if (greaterThan(items[j - 1], items[j]))                                    {                       temp = items[j - 1];                     items[j - 1] = items[j];                     items[j] = temp;                 }              }           }        }        // ...     } 

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.

Delegate Internals

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

 // ERROR: 'GreaterThanHandler' cannot // inherit from special class 'System.Delegate' public class GreaterThanHandler: System.Delegate {   ... } 

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

 public delegate bool GreaterThanHandler (   int first, int second); 

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

 class DelegateSample {   public delegate bool GreaterThanHandler (     int first, int second); } 

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

 public delegate bool GreaterThanHandler (   int first, int second); class DelegateSample {   public static void BubbleSort(     int[] items, GreaterThanHandler greaterThan)   {     ...   }   public static bool GreaterThan(int first, int second)                       {                                                                             return (first > second);                                                  }                                                                           ... } 

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

 public delegate bool GreaterThanHandler (   int first, int second); ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- class DelegateSample {   public static void BubbleSort(       int[] items, GreaterThanHandler greaterThan)   {       ...   }   public static bool GreaterThan(int first, int second)                       {       return (first > second);   }     static void Main(string[] args)   {         int i;       int[] items = new int[5];       for(i=0;i<items.Length; i++)       {           Console.Write("Enter an integer:");           items[i] = int.Parse(Console.ReadLine());       }         BubbleSort(items, GreaterThan);                                           for (i = 0; i < items.Length; i++)       {           Console.WriteLine(items[i]);       }    } } 

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

 public delegate bool GreaterThanHandler (   int first, int second); class DelegateSample {   public static void BubbleSort(       int[] items, GreaterThanHandler greaterThan)   {       ...   }     public static bool GreaterThan(int first, int second)                        {       return (first > second);   }     static void Main(string[] args)   {          int i;       int[] items = new int[5];       for(i=0;i<items.Length; i++)       {           Console.Write("Enter an integer:");           items[i] = int.Parse(Console.ReadLine());       }       BubbleSort(items,                                                              new GreaterThanHandler(GreaterThan));                                  for (i = 0; i < items.Length; i++)       {           Console.WriteLine(items[i]);       }   }      ... } 

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

 class DelegateSample {     public delegate bool GreaterThanHandler(int first,int second);      public static void BubbleSort(       int[] items, GreaterThanHandler greaterThan)   {       int i;       int j;       int temp;       for (i = items.Length - 1; i >= 0; i--)       {           for (j = 1; j <= i; j++)           {               if (greaterThan(items[j - 1], items[j]))               {                   temp = items[j - 1];                   items[j - 1] = items[j];                   items[j] = temp;               }            }         }      }      public static bool GreaterThan(int first, int second)      {          return (first > second);      }      public static bool AlphabeticalGreaterThan(                                     int first, int second)                                                  {                                                                               int comparison;                                                              comparison = (first.ToString().CompareTo(                                       second.ToString()));                                                    return (comparison > 0);                                                }                                                                             static void Main(string[] args)      {              int i;          int[] items = new int[5];          for(i=0;i<items.Length; i++)          {              Console.Write("Enter an integer:");              items[i] = int.Parse(Console.ReadLine());          }            BubbleSort(items, AlphabeticalGreaterThan);                                for (i = 0; i < items.Length; i++)          {              Console.WriteLine(items[i]);          }      }  } 

Output 13.1.

 Enter an integer:1 Enter an integer:12 Enter an integer:13 Enter an integer:5 Enter an integer:4 1 12 13 4 5 

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().

Anonymous Methods

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

 class DelegateSample {   ...   static void Main(string[] args)   {       int i;       int[] items = new int[5];         GreaterThanHandler greaterThan;                                         for(i=0;i<items.Length; i++)       {           Console.Write("Enter an integer:");           items[i] = int.Parse(Console.ReadLine());       }       greaterThan =                                                                  delegate(int first, int second)                                           {                                                                             return (first < second);                                              };                                                                   BubbleSort(items, greaterThan);                                           for (i = 0; i < items.Length; i++)       {           Console.WriteLine(items[i]);       }   }  } 

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

 class DelegateSample {   ...   static void Main(string[] args)   {      int i;      int[] items = new int[5];      for(i=0;i<items.Length; i++)      {          Console.Write("Enter an integer:");          items[i] = int.Parse(Console.ReadLine());      }      BubbleSort(items,                                                                delegate(int first, int second)                                              {                                                                                return (first < second);                                                 }                                                                         );                                                                           for (i = 0; i < items.Length; i++)       {           Console.WriteLine(items[i]);       }    } } 

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.

Advanced Topic: Anonymous Method Internals

Anonymous methods are not an intrinsic construct within the CLR. Rather, they are implemented through the C# compiler. Anonymous methods provide a language construct for an inline declared delegate pattern. The C# compiler, therefore, generates the implementation code for this pattern so that the compiler automatically writes the code instead of the developer writing it manually. Given the earlier listings, therefore, the C# compiler generates CIL code that is similar to the C# code shown in Listing 13.13.

Listing 13.13. C# Equivalent of CIL Generated by the Compiler for Anonymous Methods

 class DelegateSample {  // ...  static void Main(string[] args)  {      int i;      int[] items = new int[5];      for(i=0;i<items.Length; i++)      {          Console.Write("Enter an integer:");          items[i] = int.Parse(Console.ReadLine());      }          BubbleSort(items, Program.__AnonymousMethod_00000000);            for (i = 0; i < items.Length; i++)      {          Console.WriteLine(items[i]);      }    }    private static bool __AnonymousMethod_00000000(                   int first, int second)                                    {                                                                 return first < second;                                    }                                                          } 

In this example, an anonymous method is converted into a separately declared static method that is then instantiated as a delegate and passed as a parameter.


Outer Variables

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

 class DelegateSample {  // ...  static void Main(string[] args)  {       int i;       int[] items = new int[5];         int swapCount=0;                                                            for(i=0;i<items.Length; i++)       {           Console.Write("Enter an integer:");           items[i] = int.Parse(Console.ReadLine());       }       BubbleSort(items,                                                               delegate(int first, int second)                                             {                                                                               bool swap = first < second;                                                 if(swap)                                                                    {                                                                               swapCount++;                                                            }                                                                           return swap;                                                            }                                                                       );                                                                          for (i = 0; i < items.Length; i++)       {           Console.WriteLine(items[i]);       }       Console.WriteLine("Items were swapped {0} times.",                                            swapCount);                                                 }   } 

Output 13.2.

 Enter an integer:5 Enter an integer:1 Enter an integer:4 Enter an integer:2 Enter an integer:3 5 4 3 2 1 Items were swapped 4 times. 

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.

Advanced Topic: Outer Variable Internals

The CIL code generated by the C# compiler for outer variables is more complex than the code for a simple anonymous method because the outer variable must pass to and from the call site in a thread-safe manner. Listing 13.15 shows the C# equivalent of the CIL code used to implement outer variables.

Listing 13.15. C# Equivalent of CIL Code Generated by Compiler for Outer Variables

 class DelegateSample {        // ...     private sealed class __LocalsDisplayClass_00000001           {                                                                  public int swapCount;                                          public bool __AnonymousMethod_00000000(                             int first, int second)                                    {                                                                  bool swap = first < second;                                    if (swap)                                                      {                                                                   swapCount++;                                              }                                                              return swap;                                              }                                                          }                                                              ...  static void Main(string[] args)  {      int i;      int swapCount=0;      int[] items = new int[5];      for(i=0;i<items.Length; i++)      {          Console.Write("Enter an integer:");          items[i] = int.Parse(Console.ReadLine());      }      __LocalsDisplayClass_00000001 handler =                         new __LocalsDisplayClass_00000001();                      handler.swapCount = swapCount;                               BubbleSort(items, handler.__AnonymousMethod_00000000);       swapCount = handler.swapCount;                                 for (i = 0; i < items.Length; i++)      {          Console.WriteLine(items[i]);      }      Console.WriteLine("Items were swapped {0} times.",                        swapCount);     } } 





Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net