Functional programming with C# - Lambda expressions

Lambda expressions are a popular concept in C# and Java. It allows us to write in a readable and intuitive way anonymous functions to create delegates or expression tree types. 

This is the third part of the series about functional programming with C#. If you have not read through the first part about delegates or the second part about anonymous functions I recommend you to learn about them before continuing.

By now you understand that it is possible to store references to methods in delegate types and that these methods can be also anonymous.

Lambda Expressions

Having to write an anonymous function with the keyword delegate can be confusing because we use the same keyword when creating a delegate type as seen in SmartClass when we declare a new type that can store methods that return void and that accept a single string argument public delegate void WriteMessage(string message);

There is an easier, more readable and more intuitive way to create an anonymous method:
Notice the lambda operator => as part of the lambda expression. That's pretty much all what a lambda expression is, a way to create inline anonymous functions for a specific delegate. In this case the first part of the expression (message) represents the arguments that the delegate type accepts. This argument does not need to be explicitly annotated as a string because the C# compiler will determine its type by having a look at the delegate's signature. The right part of the expression is the code to be executed, the body of the anonymous function.

This all could even be simplified further like this:
without the curly brackets.
Find the examples on my GitLab repository

Comments