Thursday, June 2, 2016

Lambda expressions in C#

In today's blog post, I will be discussing lambda expressions in C#. They are pretty useful for writing shorthand methods and were introduced in C# 3.

Lambda Expressions

Lambda expressions are methods that appear in line and do not have a name. Lambda expressions are simply more concise syntax of anonymous methods. At compile time all lambda expressions are converted to anonymous methods. Lambda expressions are denoted using lambda operator " => ". To the left of the operator are method arguments and right side denotes the method definition.


Lambda Expressions in C#



Let's look at an example. Suppose we have a method to find multiples of five like this:

public static List<int> GetMultiplesOfFive(List<int> numbers)
{
       var multiples = new List<int>();
       foreach (var num in numbers)
       {
           if (num % 5 == 0)
           {
                multiples.Add(num);
            }
       }
       return multiples;
 }

And then we simply use this method like this:

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var multiples = GetMultiplesOfFive(numbers);

Now, that's a lot of work to create a method especially if it's being used only once in the code. Instead of creating doing all that, we can simply use lambda expression like this:

var numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var multiples = numbers.Where(x => x % 5 == 0).ToList();

This way we didn't have to create a separate method. As I mentioned this is good for any short operation that we want to accomplish without going through the overhead of creating a separate method. The compiler will do it for us :)

The variable referred inside lambda expression (i.e. "x") is not available outside the lambda expression. Also, we can have lambda expressions with multiple parameters or with no parameter. Most of the times compiler can infer the variable type in use in lambda expression, but if not, we can also provide it explicitly. For example,

(int x) => x % 5 == 0

Conclusion

So we saw how lambda expressions can be useful and help us save some time and extra code. They are more of syntactic sugar for writing methods with short definition that are not used more than once (generally).

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)

No comments:

Post a Comment