Servergeek
Mickey Williams' weblog


Powered by Blogger Pro™

Thursday, September 15, 2005

Lambda Functions with the C# 3.0 Preview


So how do Lambda functions work using the preview? I've come up with a simple example that leverages the PDC HOL lab exercise. Consider the code fragment below, which uses C# 2.0 syntax for the predicate delegate:

static List ApplyEvenFilter(List originalList)
{
    return originalList.FindAll( delegate(int n) { return (n%2) == 0;});
}
 

As you can see, with anonymous delegates we avoid the need to declare a predicate method that's only used for filtering. However, we still have a lot of procedural code plumbing. Frankly, 50% of the code is concerned with convincing the compiler that we want an online delegate. The equivalent lambda function syntax is more concise and declarative:

static List ApplyEvenFilter(List originalList)
{
    return originalList.FindAll((int i) => (i%2) == 0);
}

It turns out that this lambda function is a common case that allows us to use a simpler style. Because the type of the parameter is known, the type can be removed:

static List ApplyEvenFilter(List originalList)
{
    return originalList.FindAll(i => (i%2) == 0);
}

So -- given an anchor parameter i (the type is already knowable by the compiler), simply return true or false, depending on the parameter's value. I'll have more info on lambda functions later.


Home