Functions

C# Lambda Expressions

Lambda Expressions

C# lambda expressions use => for concise functions.

Introduction to Lambda Expressions

Lambda expressions in C# are anonymous functions that provide a concise way to represent methods. They are particularly useful for writing inline code that needs to be passed as arguments to methods or delegates. The syntax for lambda expressions involves using the => operator, also known as the 'goes to' operator.

Lambda Expression Syntax

The basic syntax of a lambda expression is:

(parameters) => expression

Or for multiple statements:

(parameters) => { statement1; statement2; }

Let's explore these with examples.

Single-Line Lambda Expression

Single-line lambda expressions are used for short, single operations. Here is an example that demonstrates a lambda expression to square a number:

Multi-Line Lambda Expression

For more complex operations, multi-line lambda expressions are used. They allow you to include multiple statements within a block. Here's an example:

Lambda Expressions with Collections

Lambda expressions are often used with collections, especially with LINQ queries. They provide a succinct way to filter, sort, and project data. Here's a simple example using a list of numbers:

Benefits of Using Lambda Expressions

Using lambda expressions in C# offers several benefits:

  • Conciseness: They allow you to write less code.
  • Readability: They can make the code easier to read and understand.
  • Flexibility: They can be used anywhere a delegate is expected.

These advantages make lambda expressions a powerful tool in a C# developer's toolkit.

Conclusion

Lambda expressions in C# simplify the process of writing inline methods, especially within LINQ queries and delegates. Understanding how to implement and utilize them can greatly enhance your coding efficiency and readability.

In the next topic, we'll explore how delegates work in C#.

Previous
Methods