Functions

.NET Lambda Expressions

Lambda Expressions

.NET lambda expressions use => for concise functions.

Introduction to Lambda Expressions

Lambda expressions in .NET provide a concise way to represent anonymous methods, allowing you to write inline functions. They are particularly useful when you want to pass a simple piece of logic as a parameter to methods like LINQ queries, event handlers, or other delegate-based APIs. The syntax of a lambda expression uses the => operator, known as the 'goes to' operator.

Syntax of Lambda Expressions

Lambda expressions are defined using the following basic syntax:

  • Parameters: Located on the left side of the => operator.
  • Expression or Statement Block: Located on the right side of the => operator.

Here's a simple example of a lambda expression that takes two integers and returns their sum:

Using Lambda Expressions with LINQ

Lambda expressions are often used with Language Integrated Query (LINQ) to perform queries on collections in a streamlined manner. For example, consider the following code that filters a list of integers to find only the even numbers:

Lambda Expressions and Delegates

In .NET, lambda expressions can be implicitly converted to delegates or expression trees. Delegates are type-safe function pointers, while expression trees represent code in a tree-like data structure. This makes lambda expressions versatile for various applications, including asynchronous programming and expression tree manipulation.

Expression-Bodied Members

In C# 6 and later, you can use lambda expressions to define expression-bodied members for concise method or property definitions. For instance:

Conclusion

Lambda expressions are a powerful feature in .NET that contribute to writing succinct and readable code. They are widely used in LINQ queries, event handling, and defining simple methods or properties. By mastering lambda expressions, you can significantly enhance the expressiveness of your C# code.

Previous
Functions