Generic Delegates and Anonymous Methods
Generics and anonymous methods are great improvements of C#.
Having a generic collection persons of type List<Person>, the objects of the collection can be accessed with a simple foreach statement:
foreach (Person p in persons)
{
Console.WriteLine(p);
}
The collection class also has a ForEach method that can be used instead of a foreach statement. The ForEach method has the parameter Action<T> action. Action is a generic delegate:
public delegate void Action<T>(T obj);
Using Person objects in the collection, the method that can be invoked by the delegate looks like this:
void DisplayPerson(Person p)
{
Console.WriteLine(p);
}
Now this method can be passed to the ForEach method:
persons.ForEach(new Action<Person>(DisplayPerson));
The same can be done with fewer characters as the delegate type is inferred if possible:
persons.ForEach(DisplayPerson);
If the method that is invoked by ForEach is not used on other places, it can be implemented as an anonymous method:
persons.ForEach(delegate(Person p)
{
Console.WriteLine(p);
});
Christian