Anonymous Method In C# With Examples

In C#, An anonymous method is an inline unnamed method in the code. It is created with the delegate keyword and does not need a name or return type.

In this article, We will discuss the Anonymous Method in C# with multiple Examples.

CSharp anonymous method
C# anonymous method

What is Anonymous Method in C#?

An anonymous method in C# is one that has no name, or return type, and only has a body. It allows a code block to be passed as a delegate parameter. You don’t need to specify a return type, because the return type is inferred from the return statement in the method body.

  • 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

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

delegate(Parameters)
{
    // Code
};

Anonymous Methods Example

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
}

Key points about the anonymous method

Following are a few important points about the anonymous methods:

  • An anonymous method is a method that doesn’t have 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 accessed inside an anonymous method.
  • The variables declared inside an anonymous method can’t be accessed 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 statement such as goto, break, continue are not allowed within an anonymous method.
  • An anonymous method can’t access ref or out parameter from an outer scope.
  • The unsafe code can’t be accessed within an anonymous method.

Using an anonymous method as an event handler

In the following example, we’ll use an anonymous method to create an event handler that will perform some action when the user clicks 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.

Using 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:

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 a 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 this article about 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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments