C# / C# Delegates, Events, and Lambdas
Exploring Lambda Expressions and Anonymous Methods
Lambda expressions and anonymous methods are a concise way of defining methods that can be used in places where delegates are required. This tutorial will teach you how to use the…
Section overview
5 resourcesCovers delegates, events, and lambda expressions for advanced programming in C#.
Introduction
Goal of the Tutorial
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.
What You Will Learn
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
Prerequisites
Before starting this tutorial, you should have a basic understanding of C# programming, including knowledge of delegates.
Step-by-Step Guide
Lambda Expressions
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) };
Anonymous Methods
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) };
Differences Between Lambda Expressions and Anonymous Methods
While lambda expressions and anonymous methods are similar, there are some important differences:
- Syntax: Lambda expressions use the
=>operator while anonymous methods use thedelegatekeyword. - Implicitly Typed: Lambda expressions can be implicitly typed, meaning the compiler can infer the type of the input parameters. Anonymous methods cannot do this.
thisScope: In a lambda expression,thisrefers to the class instance that contains the lambda expression. In an anonymous method,thisrefers to the delegate instance.
Code Examples
Example 1: Lambda Expression
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.
Example 2: Anonymous Method
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
Summary
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.
Practice Exercises
Exercise 1: Lambda Expression
Write a lambda expression that checks if a number is even or not.
Exercise 2: Anonymous Method
Write an anonymous method that checks if a string is a palindrome or not.
Solutions
Here are the solutions for the above exercises:
- Lambda Expression:
Func<int, bool> isEven = n => n % 2 == 0;
Console.WriteLine(isEven(4)); // Outputs True
- Anonymous Method:
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.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article