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…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers 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 the delegate keyword.
  • Implicitly Typed: Lambda expressions can be implicitly typed, meaning the compiler can infer the type of the input parameters. Anonymous methods cannot do this.
  • 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.

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:

  1. Lambda Expression:
Func<int, bool> isEven = n => n % 2 == 0;
Console.WriteLine(isEven(4)); // Outputs True
  1. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Unit Converter

Convert between different measurement units.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help