Delegates and lambda

Delegates and lambda

What are delegates?

A delegate is a type that represents a reference to a method (with a particular parameter list and return type). All delegates implicitly derive from System.Delegate class. C# handles callback functions and event handlers by delegates. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance!

A simple demo to create and use a delegate

using System;

namespace Delegates
{
    delegate void ArithmeticOperation(double operand1, double operand2);

    class Program
    {
        static void Addition(double number1, double number2)
        {
            Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
        }

        static void Subtraction(double number1, double number2)
        {
            Console.WriteLine($"{number1} - {number2} = {number1 - number2}");
        }

        static void Main(string[] args)
        {
            ArithmeticOperation opr;

            opr = Addition;            
            opr(10, 5);

            opr = Subtraction;
            opr(10,5);

            Console.WriteLine();
        }
    }
}

Using delegates with an anonymous method

In C# 1.0, you created an instance of a delegate by explicitly initializing it with a method that was defined elsewhere in the code. C# 2.0 introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation.

Anonymous methods in C# can be defined using the delegate keyword. By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.

using System;

namespace AnonymousMethod
{
    delegate void ArithmeticOperation(double operand1, double operand2);

    class Program
    {
        static void Main(string[] args)
        {
            ArithmeticOperation sum;
            sum = delegate (double number1, double number2)
            {
                Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
            };
            
            sum(10, 5);
            Console.WriteLine();
        }
    }
}

Using delegates with lambda expressions

C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. In general, applications that target version 3.5 and later of the .NET Framework should use lambda expressions. A lambda expression is a block of code (an expression or a statement block). It can be passed as an argument to methods, and it can also be returned by method calls! Lambda expression is a shorter way of representing anonymous methods.

A lambda expression uses =>, the lambda declaration operator, to separate the lambda's parameter list from its executable code. To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator, and you put the expression or statement block on the other side.

using System;

namespace LambdaExpressions
{
    delegate void ArithmeticOperation(double operand1, double operand2);

    class Program
    {
        static void Main(string[] args)
        {
            ArithmeticOperation sum;
            sum = (double number1, double number2) =>
            {
                Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
            };
            
            sum(10, 5);
            Console.WriteLine();
        }
    }
}

Using delegates with lambda expressions with no parameters

There can be lambda expressions without any parameters and we can use local variables in the lambda expressions as shown in the below example:

using System;

namespace LambdaExpressions
{
    delegate void PrintHello();

    class Program
    {
        static void Main(string[] args)
        {
            PrintHello sayHello;
            sayHello = () =>
            {
                string name = "Alice";
                Console.WriteLine($"Hello {name}");
            };
            
            sayHello();
            Console.WriteLine();
        }
    }
}

Additional Reading

https://itnext.io/delegates-anonymous-methods-and-lambda-expressions-5ea4e56bbd05

Last updated