C# – Anonymous Method with examples

What is Anonymous Method?

 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

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

delegate(Parameters)
{
    // Code
};

Example of an anonymous method

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
}

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

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

Important points about the anonymous method

Following are the few important points about the anonymous method

      • The anonymous method is a method without having a name and return type.
      • 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.
      • An anonymous method cannot access ref or out parameters of an outer scope.
      • The unsafe code cannot be accessed within an anonymous method.
      • The jump statements such as  goto ,  break  and  continue  are not allowed inside an anonymous method.

Hope you enjoyed this post and found it useful.

Thanks for visiting.

Leave a Reply

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

11 + 14 =