- Introducing Delegates
- Anonymous Methods
- System-Defined Delegates: Func<>
- Lambda Expressions
- Summary
Anonymous Methods
C# 2.0 and later include 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 12.11.
Listing 12.11. Passing an Anonymous Method
class DelegateSample { // ... static void Main(string[] args) { int i; int[] items = new int[5];ComparisonHandler comparisonMethod;
for (i=0; i<items.Length; i++) { Console.Write("Enter an integer:"); items[i] = int.Parse(Console.ReadLine()); }comparisonMethod =
delegate(int first, int second)
{
return first < second;
};
BubbleSort(items, comparisonMethod);
for (i = 0; i < items.Length; i++) { Console.WriteLine(items[i]); } } }
In Listing 12.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 comparisonMethod variable (see Listing 12.12).
Listing 12.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 parameter types and the return type must be compatible with the ComparisonHandler data type, the delegate type of the second parameter of BubbleSort().
In summary, C# 2.0 included a new feature, anonymous methods, that provided a means to declare a method with no name and convert it into a delegate.