Anonymous Method In C# (With Examples)

An anonymous method in C# is a method that doesn’t have a name. You can create an anonymous method using the delegate keyword and assign it to a variable of delegate type.

In this article, We will discuss about the Anonymous method with multiple examples.

CSharp anonymous method
C# anonymous method

What is Anonymous Method in C#?

An anonymous method in C# is a method without a name or return type. It consists only of the method body, which is a code block. It can be passed as a delegate parameter. The return type is automatically determined from the return statement within the method body.

Here are some simple points to understand:

  • You can create an anonymous method using the delegate keyword with optional parameters. It can be assigned to a variable of the delegate type.
  • Anonymous methods are inline statements or expressions that make the code easier to read and understand.
  • They are useful when you want to directly associate an action with an event without creating a separate event handler function.
  • Anonymous methods are useful for handling events.
  • Variables or methods declared outside an anonymous method can be accessed inside it.
  • Variables declared inside an anonymous method cannot be accessed outside of it.
  • Anonymous methods can be passed as parameters to other methods or functions.

Syntax:

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

delegate(Parameters)
{
    // Code Here.
};

Example: Anonymous Method

Here is an example of an anonymous method in C#.

using System;

class Program
{
    delegate void GreetingDelegate(string name);

    static void Main()
    {
        // Create an instance of the delegate and assign an anonymous method to it
        GreetingDelegate greeting = delegate (string name)
        {
            Console.WriteLine("Hello, " + name + "!");
        };

        // Call the delegate like a regular method
        greeting("Shekh Ali");

        Console.ReadLine();
    }
}

Code Explanation: 

In this example, we create an anonymous method using the delegate keyword. The anonymous method takes a string parameter called name and prints a greeting message to the console using the given name. 

We assign this anonymous method to a delegate named greeting.

When we call the delegate greeting("Shekh Ali"), it invokes the anonymous method, passing in the name “Shekh Ali”. 

As a result, the output will be:

Hello, Shekh Ali!

Example 2: Anonymous method in C#

Here is another example of an anonymous method in C#.

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
}

Limitations of the Anonymous Method:

The following are the few limitations of the Anonymous method:

  • Anonymous methods cannot be used to the left of the “is” operator.
  • Jump statements such as goto, break, and continue are not allowed within an anonymous method.
  • An anonymous method cannot access ref or out parameters from an outer scope.
  • Anonymous methods cannot access unsafe code.
  • Overloading an anonymous method is not possible.
  • Anonymous methods cannot be used as the target of a virtual method call.
  • Anonymous methods cannot be used as iterators or async methods.
  • Anonymous methods cannot be used with the async/await keywords.

Example 3: Anonymous method as an event handler

We will use an anonymous method to define an event handler in the given example. This event handler will execute a specific 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 the button is clicked, action will be performed directly in response to the Click event using an anonymous method, as shown in the image below.

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

As expected, a message box displays a “Hello” message when clicking the submit button.

Example 4: Anonymous method in a lambda expression

Here is an example of using an anonymous method in a lambda expression with code comments:

using System;

class Program
{
    delegate int CalculationDelegate(int a, int b);

    static void Main()
    {
        // Create an instance of the delegate and assign an anonymous method using a lambda expression
        CalculationDelegate calculation = (a, b) =>
        {
            return a + b;
        };

        // Call the delegate like a regular method
        int result = calculation(5, 3);
        Console.WriteLine("The result is: " + result);

        Console.ReadLine();
    }
}

Code Explanation:

In this example, we use an anonymous method in a lambda expression to create an instance of a delegate named calculation. The anonymous method takes two integer parameters, a and b, and returns their sum.

When we call the delegate calculation(5, 3), it invokes the anonymous method with the values 5 and 3, which results in their sum. 

The output will be:

The result is: 8

Example 5: Anonymous method as a parameter

Here is an example of using an anonymous method as a parameter in C#:

using System;

class Program
{
    // Delegate definition
    delegate void ProcessDelegate(string message);

    // Method that takes a delegate as a parameter
    static void PerformAction(string message, ProcessDelegate action)
    {
        // Execute the delegate passed as a parameter
        action(message);
    }

    static void Main()
    {
        // Call PerformAction method and pass an anonymous method as a parameter
        PerformAction("Hello World!", delegate(string message)
        {
            Console.WriteLine("Message received: " + message);
        });

        Console.ReadLine();
    }
}

Output:

Message received: Hello World!

References: MSDN – Lambda expressions

FAQs:

Here are some frequently asked questions (FAQs) about anonymous methods in C#:

Q: What is an anonymous method in C#?

An anonymous method in C# is a method that is defined without a specific name. It allows you to create and use a method directly within your code, without the need for a separate method declaration.

Q: How do I create an anonymous method in C#?

To create an anonymous method, use the delegate keyword followed by a parameter list and a code block

Q: What is the difference between lambda and anonymous methods?

The main difference between lambda expressions and anonymous methods is their syntax.

Lambda expressions provide a more concise and expressive syntax for defining and using anonymous methods. They use the => (arrow) operator to separate the input parameters from the method body. Lambda expressions are typically used in functional programming and LINQ queries.

On the other hand, anonymous methods use the delegate keyword followed by a code block to define the method. They are slightly more verbose than lambda expressions but offer more flexibility, such as allowing the use of statements like return, if, and loops within the method body.

Q: Can I return a value from an anonymous method?

Yes, you can return a value from an anonymous method by specifying the return type in the delegate declaration and using the return statement within the method’s body.

Q: Can I access variables or methods from outside an anonymous method?

Yes, you can access variables or methods declared outside an anonymous method within its body. It provides access to the outer scope.

Q: Can an anonymous method access variables declared inside it from outside?

No, variables declared inside an anonymous method cannot be accessed outside of it. They have a limited scope within the method.

Recommended Articles:

Shekh Ali
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments