This tutorial aims to introduce you to lambda expressions and anonymous methods in C#. These are powerful features of the C# language that allow you to define methods in a concise manner, especially in places where delegates are required.
By the end of this tutorial, you will have a good understanding of:
- What lambda expressions and anonymous methods are
- The differences between lambda expressions and anonymous methods
- How and when to use lambda expressions and anonymous methods
Before starting this tutorial, you should have a basic understanding of C# programming, including knowledge of delegates.
In C#, a lambda expression is an anonymous function that you can use to create delegates or expression tree types. It uses the =>
operator which reads as 'goes to'.
Here is the basic syntax of a lambda expression in C#:
(input-parameters) => { statement(s) };
An anonymous method is like a regular method but it doesn't have a name and it can be defined using the delegate
keyword. Here is the basic syntax:
delegate(parameters) { statement(s) };
While lambda expressions and anonymous methods are similar, there are some important differences:
=>
operator while anonymous methods use the delegate
keyword.this
Scope: In a lambda expression, this
refers to the class instance that contains the lambda expression. In an anonymous method, this
refers to the delegate instance.Here is an example of a simple lambda expression that adds two numbers:
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Outputs 8
In this example, Func<int, int, int>
is a delegate that takes two integers as input and returns an integer. The lambda expression (a, b) => a + b
takes two integers a
and b
, and returns their sum.
Here is an equivalent anonymous method for the above lambda expression:
Func<int, int, int> add = delegate(int a, int b) { return a + b; };
Console.WriteLine(add(5, 3)); // Outputs 8
In this tutorial, we have covered lambda expressions and anonymous methods in C#, including their syntax, differences, and usage. The next step in your learning journey could be to explore other features of C#, such as LINQ, which makes heavy use of lambda expressions.
Write a lambda expression that checks if a number is even or not.
Write an anonymous method that checks if a string is a palindrome or not.
Here are the solutions for the above exercises:
Func<int, bool> isEven = n => n % 2 == 0;
Console.WriteLine(isEven(4)); // Outputs True
Func<string, bool> isPalindrome = delegate(string s)
{
string reversed = new string(s.Reverse().ToArray());
return s == reversed;
};
Console.WriteLine(isPalindrome("radar")); // Outputs True
Continue practicing with more complex examples to strengthen your understanding of lambda expressions and anonymous methods.