C# Anonymous Methods

Summary: in this tutorial, you’ll learn about C# anonymous methods which are methods without names.

Introduction to C# anonymous methods

When assigning a method to a delegate, you define a method, either instance method or static method, and then assign it to the delegate. For example:

class Program
{
    delegate int Transfomer(int x);
    static int Square(int x)
    {
        return x * x;
    }
    public static void Main(string[] args)
    {
        Transfomer transform = Square;

        Console.WriteLine(transform(10)); // 100
    }
}Code language: C# (cs)

In this example:

First, declare a delegate called Transformer that accepts an integer and returns an integer:

delegate int Transfomer(int x);Code language: C# (cs)

Second, define a static method called Square() with the same signature as the Transformer delegate:

static int Square(int x)
{
    return x * x;
}Code language: C# (cs)

Third, assign the Square method to the Transformer delegate and invoke it inside the Main() method:

Transfomer transform = Square;
Console.WriteLine(transform(10)); // 100Code language: C# (cs)

Sometimes, defining a new method is not necessary because you only use it once. It creates unwanted overhead.

C# allows you to create a delegate and immediately assign a code block to it. This code block can be either an anonymous method or a lambda expression.

An anonymous method uses the delegate keyword followed by an optional parameter declaration and method body. For example:


class Program
{
    delegate int Transfomer(int x);

    public static void Main(string[] args)
    {
        Transfomer transform = delegate (int x) { return x * x; };

        Console.WriteLine(transform(10)); // 100
    }
}Code language: C# (cs)

In this example, we don’t define the static method Square. Instead, we assign an anonymous method to the transform delegate.

The following statement defines an anonymous method and assigns it to the Transformer delegate:

delegate (int x) { return x * x; }Code language: C# (cs)

Anonymous methods can access the outer variables. For example:


class Program
{
    delegate decimal Pricing(decimal price);

    public static void Main(string[] args)
    {
        decimal tax = 0.08m;
        decimal price = 100m;

        Pricing calculateNet = delegate(decimal price) {
            return price * (1 + tax);
        };

        Console.WriteLine(calculateNet(price));
    }
}Code language: C# (cs)

Output:

108Code language: C# (cs)

In this example, the anonymous method accesses the tax variable from the Main() method.

Starting from C# 3, you can use lambda expressions instead of anonymous methods, which have more concise syntax.

Summary

  • Anonymous methods are methods without names.
  • Use the delegate keyword to define an anonymous method.
Was this tutorial helpful ?