| Quick Introduction to Lambda Expressions |
|
|
| Written by Markus Ewald | |
| Tuesday, July 14 2009 18:56 | |
|
Because of the huge redistributable size of the .NET Framework 3.5, I have shied away from using .NET 3.5 for my own games. In fact, I'm still thinking that requiring my customers to a download 235 MB executable before they can even install my game is asking a bit much. However, if you're not distributing your application, but only its output - as is the case when you create a website in ASP.NET or ASP.NET MVC - there is no point in denying yourself these features. Coincidentally, this is what happened to me. After ignoring .NET 3.5 for some time, I decided to revamp my website using ASP.NET MVC. Deciding to use the cutting edge of website technology, modern libraries like FluentNHibernate exposed me to lamba expression with just confused me at first. After reading up on lamba expressions on MSDN, it turned out they were just syntactic sugar for anonymous delegates, which in turn are just convenient shortcuts to creating delegate methods (+ helper classes). So here's a short tutorial that will guide you from knowing only simple method calls to using lambda expressions! Simple Method CallsA normal method call is easy to understand. You define a method with some parameters and then you can call it from another place as often as you want: No explanation necessary here. Let's step up the game. Explicit DelegatesWhat if you wanted to call a method to notify a receiver about something happening, but you do want to fix the function that will be called in order to keep your code reusable?
Wouldn't it be convenient if you could assign methods to a variable just like
you can assign
Delegates are exactly that. Whereas
As you can see, we have a variable
Any method that is compatible (meaning it returns void and takes an int)
can be assigned to a variable of type Anonymous MethodsIn C# 2.0 (supported by .NET 2.0 / Visual Studio 2005 and later) this can be considerably shortened.
Whereas we declared the methods that we assigned to our delegate variable
( As a consequence, the code assigned to the delegate variable has no assigned method name, making it an anonymous method. Lamba ExpressionsWith C# 3.0, we can shorten anonymous delegates even more by reducing them to this:
Let's see, a lambda expression consists of two sides, to the left of the
The type of the parameters can be automatically deduced from the delegate
type. In the second assignment of the example above, Lambda Expressions 2Lamba expressions have an implicit built-in return statement. So if we wanted to use delegates for some calculations or perhaps filtering of some data, we can use them like this: That's all there is behind lambda expressions. You will discover that there are some pretty cool use cases for lambdas and some developers got very creative in their use, but that's for you to find out :)
|

