From Delegates to Anonymous Delegates to Lambda



"Delegate" is actually the name for a variable that holds a reference to a method

A delegate is comparable to a function-pointer; a "method handle" as an object, if you like, i.e.

Func<int,int,int> add = (a,b) => a+b;
is a way of writing a delegate that I can then call. Delegates also underpin eventing and other callback approaches.

Anonymous methods are the 2.0 short-hand for creating delegate instances, for example:
someObj.SomeEvent += delegate {
    DoSomething();
};
they also introduced full closures into the language via "captured variables"

C# 3.0 introduces Lambdas, which can produce the same as anonymous methods:

Lambda expressions are a simpler syntax for anonymous delegates and can be used everywhere an anonymous delegate can be used. However, the opposite is not true.

Lambdas can also be compiled into expression trees for full LINQ against (for example) a database. You can't run a delegate against SQL Server, for example! but:

IQueryable<MyData> source = ...
var filtered = source.Where(row => row.Name == "Ady");
can be translated into SQL, as it is compiled into an expression tree (System.Linq.Expression).


Lambda expressions and anonymous delegates have an advantage over writing a separate function: they implement closures which can allow you to pass local state to the function without adding parameters to the function or creating one-time-use objects.

Performance

If you are wondering which one is faster to execute:

A lambda expression is an anonymous function. "Anonymous function" refers to either a lambda expression or an anonymous method.

 All three will execute in the same way, with the same performance characteristics.

Comments

Popular posts from this blog

Software Testing @ Microsoft

Trim / Remove spaces in Xpath?