Using delegates C# [en-US]

For some time we have been using methods with self-made algorythms to do some standard operations like finding an object that matches a specified atribute or removing object that match that same parameter.

An example of that is searching a list of cars in order get all of those that are from brand X or searching a list of person in order to find “Uncle Sam”. In C# a tipical algorythm would be:

private static List<Person> findAllPersons(string Name)
List<Person> newList = new List<Person>();
foreach(var p in personList){
if (p.Name == Name)
return newList;

This kind of solutions have been implemented for decades however Microsoft guys have been developing some alternative solutions for this kind of algorythms in order to increase the eficiency of our .net programs execution.

The first alternative i want to talk about is a delegate. This delegates are a type that references a method. Once a delegate is assigned to a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value. In our example i will now use a delegate to show you the decrease of code using.

Our List<> class as a function called Find, with some variations like FindAll or FindLast that accept a delegate as a parameter, in the example i showed above, we could do something like tho following in order to get the same result:

Person[] foundDelegatePersons = personList.FindAll(delegate(Person p) { return p.Age>23;}).ToArray();

The other alternative is to use a specific kind of delegate, a Predicate. This predicate represents the method that defines a set of criteria and determines whether the specified object meets those criteria. These predicates differ from a normal delegate because it has a boolean return value that return true if obj meets the criteria defined within the method represented by this delegate; otherwise, false. In the next example i do the same i did with the delegate however has you can see the code is pretty much easier to read.

Person[] foundPersons = personList.FindAll(new Predicate<Person>(p=>p.Age>23)).ToArray();
Running the console application i built to show that they all do the same, you can see the result:


Ok, now you might be asking youselves whats the diference between all of the options and to help you deciding i must say they all do the same however in terms of efficience the thing becomes different…

In order to verify this i made a simple test, added a stopwatch to the same code to see their execution times and the result is the following:

My algorythm takes in average 850 ticks to complete, the predicate 315 and the delegate 211. This is an average taken from 25 observations.


As you can see the number of lines you make dont say anything about the efficiency of the functions. The faster methos is the delegate one however the fancy code is the predicate one.

This is just an introduction to delegates and predicates, so start using them cause they are there to make your programmer life easier!!

Download the source code:


Rui Machado


Deixe uma Resposta

Preencha os seus detalhes abaixo ou clique num ícone para iniciar sessão:

Logótipo da

Está a comentar usando a sua conta Terminar Sessão /  Alterar )

Google+ photo

Está a comentar usando a sua conta Google+ Terminar Sessão /  Alterar )

Imagem do Twitter

Está a comentar usando a sua conta Twitter Terminar Sessão /  Alterar )

Facebook photo

Está a comentar usando a sua conta Facebook Terminar Sessão /  Alterar )


Connecting to %s