Monday, April 30, 2012

Delegates and Lambda Expressions


This chapter has been excerpted from book "Essential C# 4.0" with permission from Addison-Wesley"
Introducing Delegates

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. 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 12.1 shows the BubbleSort() method.

Listing 12.1: BubbleSort() Method
    static class SimpleSort1    {
        public static void BubbleSort(int[] items)
        {
            int i;
            int j;
            int temp;
            if (items == null)
            {
                return;
            }
            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 12.2.

Listing 12.2: BubbleSort() Method, Ascending or Descending
class SimpleSort2{public enum SortType{
Ascending,
Descending
}
{
int i;int j;int temp;if(items==null)
{
return;
}
for (i = items.Length - 1; i >= 0; i--)
{
for (j = 1; j <= i; j++)
{
switch (sortOrder)
{
{
temp = items[j - 1];
items[j - 1] = items[j];
items[j] = temp;
}
break;
{
temp = items[j - 1];
public static void BubbleSort(int[] items, SortType sortOrder)case SortType.Ascending :if (items[j - 1] > items[j])case SortType.Descending :if (items[j - 1] < items[j])
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, randomize the collection, or order them via some other criterion, it would not take long before the number of Bubble- Sort() methods and corresponding SortType values would become cumbersome.

No comments:

Post a Comment