C# Anonymous Functions

In C#, anonymous functions are functions that do not have a name and are typically used when you need to pass a function as a parameter to another function or when you want to define a small, one-off function without explicitly creating a separate method.

There are three types of anonymous functions in C#:

  1. Anonymous Methods: Anonymous methods were introduced in C# 2.0 and are defined using the delegate keyword. They allow you to define a code block with parameters and optionally a return type. Here’s an example:
delegate int Calculate(int x, int y);

static void Main()
{
    Calculate add = delegate(int x, int y)
    {
        return x + y;
    };

    int result = add(5, 3);
    Console.WriteLine(result); // Output: 8
}

In the above example, we define an anonymous method using the delegate keyword and assign it to a delegate variable add. The anonymous method takes two integers as parameters and returns their sum.

  1. Lambda Expressions: Lambda expressions provide a more concise syntax for defining anonymous functions. They were introduced in C# 3.0. Lambda expressions are typically used with functional interfaces or delegate types. Here’s an example:
Func<int, int, int> add = (x, y) => x + y;

int result = add(5, 3);
Console.WriteLine(result); // Output: 8

In the above example, we define a lambda expression using the => syntax. The lambda expression takes two integers as parameters and returns their sum. We assign it to a Func<int, int, int> delegate variable add and then invoke the delegate to get the result.

  1. Anonymous Function with the delegate keyword: C# 2.0 also introduced a shorter syntax for defining anonymous functions using the delegate keyword without explicitly declaring the delegate type. Here’s an example:
Func<int, int, int> add = delegate(int x, int y)
{
    return x + y;
};

int result = add(5, 3);
Console.WriteLine(result); // Output: 8

In this example, we define an anonymous function using the delegate keyword, similar to the anonymous method. However, instead of explicitly declaring the delegate type, we use the Func<int, int, int> delegate type to infer the parameter and return types.

All three types of anonymous functions provide a way to define and use functions without explicitly naming them. They are particularly useful when working with higher-order functions, such as passing functions as arguments or using them in LINQ queries.