Anonymous Method In C# with examples

In c#, An anonymous method is a method that has no name and allows us to create delegate instances without writing a separate method.

Anonymous Methods In C#
Anonymous Method

What is Anonymous Method In C#?

 Anonymous method  : In C#, An anonymous method is a method without name and return type.

It can be created using the delegate keyword with the optional parameters and can be assigned to a variable of the delegate type.
An anonymous method is an inline statement or expression which makes the code easy and more readable.

An anonymous method is useful when we want to hook an action directly to an event without separately creating an event handler.

Syntax to declare an anonymous method in C#

The following is the syntax to declare an anonymous method in C#.

delegate(Parameters)
{
    // Code
};

Example of an anonymous method in C#

An anonymous method is the same as a regular method. It allows us to write an inline code statement to execute the business logic without explicitly creating a new named method.

The following is an example of the anonymous method.

using System;
namespace AnonymousMethodDemo
{
    class Program
    {
        // Declaring a delegate
        public delegate int MyDelegate(int num1, int num2);

        static void Main(string[] args)
        {
            // Instantiating the delegate using an anonymous method

         MyDelegate myDelegate = delegate (int num1, int num2)
         {
            return num1 + num2;
         };

            Console.WriteLine(myDelegate(10,20));

        }
    }
    // Output: 30
}

Important points about the anonymous method in C#

Following are the few important points about the anonymous methods:

      • An anonymous method is a method without having a name and return type.
      • In C#, An anonymous method can be created using the delegate keyword and can be assigned to a variable of the delegate type.
      • An anonymous method can be used in event handling.
      • The variables or methods declared outside can be access inside an anonymous method.
      • The variables declared inside an anonymous method can’t be access outside the anonymous method.
      • Anonymous methods can be passed as parameters.

Limitations of the Anonymous Method

      • An anonymous method cannot be used to the left of the is operator.
      • The jump statements such as  goto ,  break  and  continue  are not allowed inside an anonymous method.
      • An anonymous method cannot access ref or out parameters of an outer scope.
      • The unsafe code cannot be accessed within an anonymous method.

Using an anonymous method as an event handler

In the following example, We are creating an event handler using an anonymous method to perform some action when the user will click on the submit button on the window form.

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
           
    private void Form1_Load(object sender, EventArgs e)
        {
            // Creating Click Event handler using an Anonymous method
            btnSubmit.Click += delegate(object obj,EventArgs arg)
            {
                MessageBox.Show(" Hello !", "Anonymous method example");
            };

        }

    }
}

When we click on the button, an action will perform directly to the Click event using an anonymous method as shown in the below image :

Anonymous method example
Event handler using an Anonymous method in C#

As expected a message box is displayed with a hello message after clicking on the submit button.

Anonymous Methods And Lambda Expressions In C#

The lambda expression is an anonymous method that can be used to create delegates or expression tree types.Lambda expressions were introduced in C# 3.0 and provide many advantages over anonymous methods.

To separate the lambda’s parameter list from its content, use the => lambda declaration operator. The following two types of lambda expressions can be used:

      • Expression lambdas: An expression lambda is a lambda expression with an expression on the right side of the => operator. The output of an expression is returned by an expression lambda, which has the following basic form: (input_parameters) => expression 
      • Statement lambdas: The only difference between a statement lambda and an expression lambda is that the statements are contained in braces:         (input_parameters) => { <sequence_of_statements> }          

Example: Statement lambdas

The body of a statement lambda can include any number of statements; however, in reality, no more than two or three are usually used.

public class CSharpAnonymousMethodExample
    {
        static void Main(string[] args)
        {
            // Example: Creating anonymous function using statement lambda
            Action<string> greet = name =>
            {
                string greeting = $"Hello {name}!";
                Console.WriteLine(greeting);
            };
            greet("Shekh Ali");
            // Output:
            // Hello Shekh Ali!

            Console.ReadKey();
        }
    }

Note: You can’t create expression trees with statement lambdas.

According to Jon Skeet, “Expression trees are a technique of expressing logic such that other code can interrogate it.

Example: A lambda expression’s input arguments

A lambda expression’s input parameters are enclosed in parentheses. Use empty parenthesis to specify zero input parameters:

Let’s have a look at some code in action.

static void Main(string[] args)
        {
            Action line = () => Console.WriteLine("Hello World!");
            line();
            Console.ReadKey();
        }

Parentheses are optional when a lambda expression has only one input parameter:

static void Main(string[] args)
        {
            Func<double, double> cube = x => x * x * x;

            Console.WriteLine($" Cube of 5 = {cube.Invoke(5)}");
            Console.ReadKey();
        }
        // Output:
        // 125

In the lambda expression, two or more input parameters are separated by comma:

static void Main(string[] args)
        {
            Func<int, int, bool> IsEqual = (x, y) => x == y;

            Console.WriteLine($" {IsEqual(5,10)} ");

            Console.ReadKey();
        }
        // Output:
        // False

References: MSDN – Lambda expressions

I hope you enjoyed and learned something from this article on Anonymous methods in C#. Please leave a comment if you notice anything that is inaccurate or if you have additional knowledge on the subject.

Recommended Articles

Leave a Reply