C# Lambda Expressions (Anonymous Methods) Tutorial

In this tutorial we learn about methods without access modifiers, names and return statements in C#, lambda expressions (anonymous functions).

We cover how to use the built-in generic delegates func and action, as well as local delegate methods.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What is a lambda expression (anonymous function)

A Lambda expression is an anonymous method. That means, it’s a method that has no access modifier, no name, and no return statement.

With Lambda expressions we can write less code, and the code will be more readable.

A lambda expression uses the lambda operator => which means goes to.

Syntax:
arguments => expession

The expression reads: arguments goes to expression.

Before we get to the example, let’s first recap how a common method works.

Example:
using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine(Square(5));
            Console.ReadLine();
        }

        static int Square(int num)
        {
            return num * num;
        }
    }
}

In the example for a normal method above, we declare a method called Square of type int with one input parameter of type int. It multiplies the number and returns the result.

In the Main() method we call our Square method with an int as a parameter.

We can convert this function into a Lambda expression. This is what it would look like:

Example:
num => num * num;

This expression would read: num goes to calculation (num * num).

This expression is short and easily readable once we get used to it. The catch though, is that a Lambda expression must be assigned to a delegate.

This can be done in one of two ways. We can use one of the built-in .NET delegates or provide our own local method.

Built-in generic delegate Func

The generic Func represents a method that takes 0 or more arguments of type and returns an out value of .

Syntax:
 Func<T, out T> method_name;
Example:
using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            Func<int, int> square = Square;

            Console.WriteLine(square(5));
            Console.ReadLine();
        }

        static int Square(int num)
        {
            return num * num;
        }
    }
}

In the example above, we have the same Square method that takes in a int number, multiplies it by itself and returns the result.

In the Main() method we declare our Func delegate and point it to the Square method.

We used as our generic types. The first int is the type for the parameter input. The second int is the return type.

Finally, we do a function call of the delegate and print it out to the console.

Func Lambda

Now that we know how to use Func, let’s see how we use it to write a Lambda expression.

Example:
using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            Func<int, int> square = num => num * num;

            Console.WriteLine(square(5));
            Console.ReadLine();
        }

        //static int Square(int num)
        //{
        //    return num * num;
        //}
    }
}

In the example above, we replace the pointer to the Square method with the Lambda expression, which reads num parameter goes to calculation (num * num) and returns the result into the Func.

We can call the Delegate as we would normally.

The Square method can be removed, we don’t need it. In this case we comment it out for you to better see how the Lambda expression works.

Built-in generic delegate Action

The generic Action represents a method that takes 0 or more arguments of type and returns void.

Syntax:
Action<T> method_name;
Example:
using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            Action<string> Log = Message;

            Log("Hello there");
            Console.ReadLine();
        }

        static void Message(string msg)
        {
            Console.WriteLine(msg);
        }
    }
}

In the example above we create a Message method that takes in a string that’s printed to the console.

In the Main() method we declare our Action delegate and point it to the Message method.

We used as our generic type, which is the type of the input parameter in the Message method.

Finally, we do a function call of the delegate with our string that we want to print to the console.

Action Lambda

Now that we know how to use Action, let’s see how we use it to write a Lambda expression.

Example:
using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            Action<string> Log = msg => Console.WriteLine(msg);

            Log("Hello there");
            Console.ReadLine();
        }

        //static void Message(string msg)
        //{
        //    Console.WriteLine(msg);
        //}
    }
}

In the example above we replace the pointer to the Message method with the Lambda expression, which reads: msg parameter goes to Console.WriteLine(msg) and returns the result into the Action.

We can call the Delegate as we would normally.

The Message method can be removed, we don’t need it. In this case we comment it out for you to better see how the Lambda expression works.

Local delegate method

The second, and less complex, way of assigning a Lambda to a delegate is the local delegate method.

Syntax:
return_type method_name(input_type input_name) => lambda_expression;

The method is declared as normal. But, where the body should be, we go directly into the Lambda expression.

Example:
int Square(int num) => num * num;

Which would be the same as writing:

Example:
int Square(int num)
{
    return num * num;
}

Calling the local method is the same as a normal method call.

Example:
Square(5);
Example:
using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            int Square(int num) => num * num;
            Console.WriteLine(Square(5));

            void Message(string msg) => Console.WriteLine(msg);
            Message("Hello there");

            Console.ReadLine();
        }
    }
}

In the example above, we create a local method called Square. In the Lambda expression we do the calculation, and print the local method call to the console.

Then, we create a local method called Message. In the Lambda expression we print the input parameter to the console, and call the method to print at runtime.

Summary: Points to remember

  • A lambda expression is a method that doesn’t have an access modifier, name or return statement.
  • A lambda expression is used with the => operator and must be assigned to a delegate.
    • The Func delegate takes arguments of type T and returns a value of T.
    • The Action delegate take arguments of type T and returns void.
  • The easiest way to write a lambda expression is by using a local delegate.
    • A method body is replaced by the lambda expression.