From Delegates to Anonymous Delegates to Lambda
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:
they also introduced full closures into the language via "captured variables"someObj.SomeEvent += delegate {
DoSomething();
};
C# 3.0 introduces Lambdas, which can produce the same as anonymous methods:
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
Post a Comment