When the client code wishes to handle an event, it should define a method that matches the signature of the associated delegate. This method is called an event handler. For example
It puts a coding overhead in instantiating delegates since a separate method has to be written. Moreover, these event handlers are not called from any part of the program other than the invoking delegate.
It is possible to associate a delegate directly to a block of statements at the time of an event registration. Delegate keyword is used to declare this block of code. It is called an anonymous method. It is also known as inline delegate.
Anonymous method is a method without name, it provides us a way of creating delegate instances without having to write a separate method or a function, as shown above.
The code given above is rewritten, using anonymous method, as shown below.
Here, you can see the Red square is the replacement of function (FindEmp()) in the first example.
Lambda expressions
As I explained about Anonymous methods, it helps to write the code blocks in-line, where delegates are required.
For example
- int res = list.Find(delegate(int n)
- {
- if (n == 5) return true;
- else return false;
- });
As you can see here in the example given above, anonymous method syntax is bit harder to write and manage.
In C#3.0 Lambda expressions are introduced. It provides a simple, more concise, functional syntax to write anonymous methods. The word lambda is taken from the lambda calculus, where everything is expressed in terms of functions.
A lambda expression is written as a parameter list, followed by the => (termed as “goes into”) symbol, followed by an expression or a statement block. Lambda expression is written, as shown below.
- ArgumentsToProcess => StatementsToProcess
There are two types of Lambda expressions,
- Expression Lambda
It has only one expression, with no curly brace or return statement.
- Statement Lambda
It is a collection of statements.
The example written with anonymous methods can be rewritten, using expression lambda. In the code given below, Find() method of generic List<T> class takes lambda expression to search.
The search is based on a particular criterion (for ex: if 3 found in the list).
Output
If the expression needs to process multiple lines of code, statement lambda can be used. In the example given below, FindAll() method of generic List<T> class is used. It returns all the elements, which match the conditions defined by the specified condition.