C# Lambdas Part 1, a Quick Overview with Examples
Download full source code.
I have tried a few times to write a blog post about using C# lambdas, and each time I have been unable to finish it. Lambdas can be a little confusing at first, and as they get more complex, can be very confusing.
There isn’t one single way to write a lambda or use a lambda, and there isn’t one way to explain them either.
In the past, I have tried to find a way to explain it all in a few sentences, and that is why I couldn’t finish those posts.
In this post, I will show many examples of using lambdas with comments to explain what is going on.
The sample code uses Func
s and Action
s, if you are not familiar with them check two posts I wrote on the topic - Actions and Funcs.
A quick overview
This may not be strictly correct, but it is how I understand them. If there is something egregiously wrong, let me know in the comments.
To my mind, a lambda is a way of writing a method, and just like a traditional method, it can take parameters (or none), and return any type (or none).
Why use a lambda?
A lambda can be invoked or passed to another method, where it will be invoked. That other method can pass parameters into the lambda.
This allows us, the program writers to decide how another method does something. Let me give a couple of concrete examples -
Polly, the resilience framework lets you retry failed HttpClient requests. Of course Polly can not know what request you want to make, so you pass a Polly Retry method a lambda that makes a HTTP request. The Retry method invokes the lambda you wrote and builds in all the resilience code necessary to retry the request.
var httpResponseMessage = await retryPolicy.ExecuteAsync(() => httpClient.GetAsync("/"));
If you have a list of numbers and you want to use a LINQ Where on the list, the Where method can take a lambda that YOU define to return only the numbers you want. You could instead write a traditional method to pass to the Where method, but that would be more code than the lambda, and may be less readable.
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var evenNumbersStatementLambda =
numbers.Where( // Where is a LINQ method that takes a Func<int, bool> to perform the filter.
(numFromNumbers) => // The lambda is passed a parameter of type int by the Where method.
{ // this is called a statement lambda, the statement(s) to the right of => are enclosed in braces and has an explicit return statement.
return numFromNumbers % 2 == 0; // The lambda returns true if the number is even.
} // this lambda is executed for each number in the numbers list.
);
var evenNumbersExpressionLambda = numbers.Where( // the lambda can be written more succinctly.
numFromNumbers => // this is an expression lambda, the statement to the right of => is not enclosed in braces. An explicit return statement is not used.
numFromNumbers % 2 == 0 // an explicit return is not needed
);
More examples
There are many ways to work with and use lambdas. The rest of this post is sample code, with detailed comments explaining what each line does (I don’t repeat comments if the code is identical to something already explained).
I strongly encourage you to step through the code line by line to see what is being executed, what parameters are being passed, and what is being returned.
A .NET Fiddle of the code is available here.
I know the comments are a little difficult to read in this blog post, but please download the attached zip file or open the .NET Fiddle.
|
|
I will write a follow up post with a few more examples of lambdas that are a little more complicated.
Download full source code.