Language: EN

csharp-funciones-lambda

What are and how to use lambda functions

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).

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 and y
  • Returns their sum as the result. :: ::::

Practical Examples

:::::::