Jul 24, 2008
On Lambdas
Someone at work complained today that she didn’t like the code she’d written to find an element in a collection:
public class SingletonSomething
{
public void DoSomething()
{
IList list;
// ..
this.Host = GetHost();
Uri item = list.Find(FindUriByHost);
}
public bool FindUriByHost(Uri uri)
{
return uri.Host == this.Host;
}
}
On the one hand, she was using IList<T>.Find(Predicate<T> predicate) which is a neat abstraction for iterating a list to find an item. However, she was having to store some state in her singleton class about the condition to apply, which she wasn’t happy about (it’s clearly not thread-safe for a start).
First of all, thinking it was a .NET 2.0 project, I suggested she use an anonymous delegate as the predicate instead of a named method. We tried this but couldn’t convince the compiler that it satisfied the Predicate<T> type:
string host = GetHost();
Uri item = list.Find(delegate(Uri uri) { return uri.Host == host; });
(I thought this would work but it didn’t–I need to look into why.)
When I realised this was a .NET 3.5 project, I suggested a lambda instead. My colleague’s first reaction was one of skepticism–she’d not really heard good things about lambdas. But after changing the code to use a lambda, and once she’d got past the funny syntax, she was quite happy with the lambda:
string host = GetUri();
Uri item = list.Find(uri => uri.Host == host);
I think we can all agree that this is much more readable, once you realise => should be read as ’such that’ or ‘goes to’:
Find a URI in the list such that uri.Host equals host
And once you’ve seen the syntax and used it a couple of times, it’s really not that complicated: much simpler than dealing with thread safety or declaring a new method. Yet, lambdas seem to have attracted a bad name. I’m not sure why.
Perhaps it’s that they seem type-less, like var (C# developers see any attack on strong typing as tantamount to sleeping with the vicar). In fact, lambdas aren’t typeless, just as var isn’t variant: the compiler simple infers the type at compile time. Once compiled, it’s as if you’d typed it in yourself. Or perhaps it’s the funny syntax, which can take several different forms.
Either way, it’s a shame. Lambdas in C# are an extremely powerful construct. I hope C# developers can come to love lambdas just as much as they love, say, type safety.