ANONYMOUS FUNCTIONS AND LAMBDA EXPRESSIONS

Not all functions are important enough to have a name. C# has supported anonymous functions since version 2.0, and a second syntactic variation — lambda expressions — was introduced in version 3.0. Generally speaking, these are functions that don’t live on the class level and that don’t have names. References to such functions are stored in variables, so effectively the function can be called wherever the reference to it is available.

Technically speaking, there are certain restrictions in place on anonymous functions. One is particularly unfortunate, and that’s the fact that they can’t be generic (more on generics in Chapter 4). They also can’t be used to implement iterators (more on iterators in Chapter 5), which is another desirable thing. But apart from that, anonymous functions can do almost everything “normal” methods can do. The term anonymous functions is a bit diluted because it can be a general term that encompasses all types of functions that don’t have names, but it can also be used as a name for the C# 2.0 feature specifically. The feature was really called anonymous methods, but anonymous functions is widely used as an exchangeable term.

Here’s what one of the earlier comparison functions could look like in C# 2.0 syntax:

static void AnonymousMethods( ) {

  Bubblesorter.IsAGreaterThanBDelegate compareInt =

    delegate(object a, object b) {

      return ((int) a) > ((int) b);

    };

}

As you can see, the keyword delegate ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.