C# Anonymous Functions: Lambda Expressions and Anonymous Methods

Enhance your C# code with anonymous functions—lambda expressions and anonymous methods. This tutorial explains their syntax, usage, and key differences, demonstrating how to create concise, inline functions for improved code readability and efficiency, especially within LINQ queries and delegate assignments.



Anonymous Functions in C#: Lambda Expressions and Anonymous Methods

Anonymous functions in C# are functions that are not declared with a name. They are very useful for creating short, concise functions that are used in specific places in your code, rather than defining a separate named method. C# provides two main types of anonymous functions: lambda expressions and anonymous methods.

Lambda Expressions

Lambda expressions are a compact way to define anonymous functions, particularly useful for creating delegates or for use within LINQ (Language Integrated Query) queries. They often improve code readability by keeping related code together.

Syntax


(input-parameters) => expression

The input parameters are enclosed in parentheses, followed by the `=>` operator (lambda operator), and then the expression representing the function's logic.

Example: Lambda Expression for Squaring a Number


using System;

public class LambdaExample {
    public static void Main(string[] args) {
        Func<int, int> square = x => x * x; //Lambda expression creating a delegate
        Console.WriteLine(square(5)); // Output: 25
    }
}

Anonymous Methods

Anonymous methods provide similar functionality to lambda expressions but use a more traditional function declaration style. They're less concise than lambda expressions but can be useful in certain scenarios, especially when you need more complex logic.

Syntax


delegate void MyDelegate(string message);

MyDelegate myDelegate = delegate(string msg) {
    Console.WriteLine(msg);
};

Example: Anonymous Method


using System;

public class AnonymousMethodExample {
    public delegate void MyDelegate();
    public static void Main(string[] args) {
        MyDelegate myDelegate = delegate() { Console.WriteLine("Anonymous method called!"); };
        myDelegate();
    }
}