I’ve been reading a lot about F# and functional programming, and it has indeed been pretty head-turning but it’s really powerful if you know how to use it. Type Inference in F# compiler is spectacular compared to the C# one, but I shall not digress. This post is about showing off the functional aspects of C# 3.0, namely Higher Order Functions. In short, higher order functions are functions that can take in one or more functions as input parameters, as well as return a function as an output. In C# 3.0, delegates have evolved a lot and with the introduction of the System.LINQ namespace, plus a lot of functional features have been incorporated into the language, and we’ll see how to make full use of them.
In the System.LINQ namespace, you will find a large bunch of Extension Methods for IEnumerable<T> class. Most of them are higher order functions, meaning that they take in a delegate (or pointer to a function) as an input parameter. Some of these delegate types taken as inputs are Func<T, TResult>, Action<T> and Predicate<T>. What this means is that you can pass in an Anonymous Function (Lambda Expressions and Anonymous Methods) to enable different kind of behaviors. If you’re familiar with the Strategy Pattern, programmers use this pattern in order to “plug in” different behaviors flexibly by writing a family of algorithms encapsulated within derived strategy classes. With higher order functions, I’m inclined to believe that we now have something more straightforward and powerful at our disposal.
Read the rest of this entry »