Lambda expressions, expression-bodied members, and anonymous methods
Modern C# syntax offers a set of powerful tools for expressing complex functionality with elegance and brevity. Let’s take a closer look at these language features and how we can use them to make our code more functional, readable, and maintainable.
What are lambda expressions?
Lambda expressions, denoted by the =>
symbol, are a succinct way to create anonymous functions. Most likely, you use them daily when working with LINQ and similar functional programming constructs.
So, let’s look at the following example where we define a lambda to square a number:
Func<Book, int> getWordCount = book => book.PageCount * 250;
This defines a lambda expression that takes an integer, x
, and returns its square. We can then use this function like so:
int wordCount = getWordCount(book);
Lambda expressions offer great flexibility in parameter types and return values. They can take multiple...