Anonymous Methods

Introduction

An anonymous method is a method without a name, which is used as a parameter for the delegate.

As we know that an instance of a delegate is created by explicitly initializing it with a method that was defined elsewhere. To further this, there is a concept of anonymous methods through which we can write an unnamed block of code that can be executed in a delegate invocation. What I mean by this is that when a method is declared and defined, we have a name to refer to that method which is nothing but a block of code. Now instead of giving any name to the method, we can directly write that block of code at the place of delegate instantiation, where we earlier were providing a name of a method.

In computer programming, an anonymous function is a function definition that is not bound to an identifier

Wiki

To create an anonymous method in C#, we can define using the delegate keyword and can be assigned to a variable of delegate type.

For example:

using System;

namespace Operations
{
    public delegate void AdditionDelegate(int x, int y);

    class Program
    {
        static void Main()
        {
            AdditionDelegate additionDelegate = delegate (int a, int b)
            {
                Console.WriteLine($"Addition of two number is: {a + b}");
            };

            additionDelegate(10, 5);
            Console.ReadLine();
        }
    }
}

If you observe the above code, we created anonymous method and passing it as a delegate parameter and assigned to a variable of the delegate type.

Anonymous Methods, anonymous types in c#, advantages of anonymous methods in c#, Anonymous Methods in C#, Delegates, Anonymous Methods and Lambda Expressions

Anonymous methods are useful when the user wants to create an inline method and also wants to pass parameters in the anonymous method like other methods. it is useful to reduce the coding overhead in instantiating delegates because we don’t have to create a separate method but remember that we should generally not use the anonymous methods, we should use them only when the code block is very small. The only advantage of an anonymous method is less code, i.e., we are not required to specify any access modifier, there is no need to specify any return type and there is no need of giving the code block a name. We simply make use of the “delegate” keyword and specify the parameter list and just write the block of code.

The reason why there is no need of giving the return type in the anonymous method is that when we are defining a delegate, the return type is specified there, so it automatically understands what the anonymous method is going to return.

Anonymous Methods variable scope

In anonymous methods, if we define any parameters inside the Anonymous Methods then those can be accessed only within the anonymous method block but the anonymous methods can access the variables which we define in outer functions scope.

For example

using System;

namespace Conversion
{
    public delegate void AdditionDelegate(int x, int y);

    class Program
    {
        static void Main()
        {
            const int addToAddition = 50;

            AdditionDelegate additionDelegate =
            delegate (int a, int b)
            {
                var sum = a + b + addToAddition;
                Console.WriteLine($"Addition of two number is: {sum}");
            };

            additionDelegate(10, 5);
            Console.ReadLine();
        }
    }
}

If you observe the above code, Our created anonymous method can access the variable “addToAddition” variable which we define in outer functions scope. But the Out function in our case i.e. “Main” can not access variable “Sum” which is defined inside the anonymous method.

Anonymous Method as Parameter

Anonymous methods can also be passed to a method that accepts the delegate as a parameter.
For example:

using System;

namespace Conversion
{
    public delegate void AdditionDelegate(int x, int y);

    class Program
    {
        static void Main()
        {
            const int addToAddition = 50;

            AdditionDelegate additionDelegate =
            delegate (int a, int b)
            {
                var sum = a + b + addToAddition;
                Console.WriteLine($"Addition of two number is: {sum}");
            };

            AdditionLogger(additionDelegate, 10, 5);
            Console.ReadLine();
        }

        static void AdditionLogger(AdditionDelegate additionDelegate, int a, int b)
        {
            additionDelegate(a, b);
            Console.WriteLine($"Logger.Log Perform Addition of number {a}, {b}");
        }
    }
}

Points to remember – Overview

  • Anonymous methods do not have a name.
  • It is useful when the user wants to create an inline method and also wants to pass parameters in the anonymous method like other methods.
  • In anonymous methods, if we define any parameters those can be accessed only within the anonymous method block.
  • We can pass anonymous methods as a parameter to the other methods.
  • It allows us to use jump statements such as goto, break, and continue inside the method in C#.
  • Anonymous methods cannot access ref or out parameters of an outer scope.
  • Anonymous methods are not allowed on the left side of is operator.
  • Anonymous methods cannot be used with unsafe code.

You can test your knowledge by free online anonymous methods quiz, also here is the collection of Anonymous methods Interview Question.

Leave a Reply

Your email address will not be published. Required fields are marked *