A lambda function in C# is a concise syntax for defining an anonymous function that can be defined inline without the need to formally name it.
These functions are useful for writing code in a more compact and readable way. They are especially helpful in situations where you need to define a simple function that you will use only once (such as in filtering, mapping, or reducing collections).
If you want to learn more about Lambda functions
check out the Introduction to Programming Course read more
Syntax of lambda functions
The basic syntax of a lambda function in C# is as follows:
(parameters) => expression
- Parameters: These are the input parameters of the lambda function, separated by commas if there is more than one.
- Expression: This is the expression that is evaluated and returned as the result of the lambda function.
Basic Example
Let’s see it with an example. The following lambda function adds two numbers:
var add = (x, y) => x + y;
:::explain
:::explain
Console.WriteLine(add(5, 3)); // Output: 8
Here we have,
- The lambda function takes two parameters
x
andy
- Returns their sum as the result. :: ::::
Practical Examples
In LINQ expressions
Lambda functions are commonly used in LINQ expressions to perform query operations on data collections.
For example, to filter a collection,
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evens = numbers.Where(num => num % 2 == 0);
Transforming a collection,
var names = new List<string> { "Luis", "María", "Pedro" };
var messages = names.Select(name => $"Hello, {name}!");
In general, for most expressions used in LINQ.
Delegates
Lambda functions can be assigned to delegate type variables to pass them as arguments to other functions or methods.
var printMessage = message => Console.WriteLine(message);
printMessage("Hello from a lambda function!");
Events
Lambda functions are useful for subscribing to events in a more concise and expressive way.
Button button = new Button();
button.Click += (sender, e) => Console.WriteLine("Button clicked");
:::::::