If you are a .NET programmer and trying to stay current you are probably looking at the current BETA (2) of Visual Studio 2005 and wondering whats new. One of the big changes in .NET 2.0 is the introduction of generics into the runtime and the inclusion of a number of stock standard generic types into the base class library.

I’m not going to go into the whole generic type system in this post since there has been heaps written about the implementation details already, but I did want to look at some of the new methods that we get on the generic collection classes and how they use generics and anonymous methods to allow C# programmers to write much more expressive code.

Find(…) and FindAll(…) Methods and the Predicate<T> Delegate

If you take a look at the List<T> type in System.Collections.Generic namespace you will see that it has a Find and FindAll method. Both of these methods take a Predicate<T> which is a generic delegate type. What the hell is a “predicate”?

Well – it depends on who you ask. Most English majors would probably give you a definition which would have you scurrying off to the dictionary to try and understand what they just said, however, if you ask a programmer then they would probably tell you something like this.

A predicate is a condition against which a piece of data is evaluated against to determine whether that condition is true or false. Basically, its a piece of code that returns true or false depending on the input.

So lets apply this ground breaking knowledge to the purpose of finding the elements of a collection. By passing as Predicate<T> to the Find or FindAll methods we are asking the collection to return us object(s) that match the condition specified by the code that the predicate points to:

PredicateWithoutAnonymousMethods

Thats pretty straight forward, but what gets interesting is when you mix generic predicates with anonymous methods, a C# specific feature that happened to be the subject of the first post this blog over twelve months ago. With anonymous methods, the above code could be expressed as:

PredicateWithAnonymousMethods

I’ll leave it to you to decide for yourself which implementation is more elegant. Back when I posted the first article to this blog I suggested that users of anonymous methods evaluate their readability, and I think that still holds true – I wouldn’t make a global ruling.

Just for kicks, consider this implementation – how would you do it without anonymous methods?

Lambda

You can download the demo code from here.