Anonymous method in C#

Introduction

In this article I am going to explain what is anonymous method, why we use that and where we use that.

Summary

In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods

most of the people found Delegates, Anonymous methods, and Lambda Expressions very confusing in .NET. I will try to distinguish between these three.

Delegates

In my previous article i have explained that that delegates are used to reference any methods that has the same signature as that of the delegate. In other words, you can call a method that can be referenced by a delegate using that delegate object. reed more..

Anonymous methods

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are basically methods without a name, having method body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions (C# Programming Guide). This kind of function offers more flexibility than a lambda expression. By using the delegate keyword, you can add multiple statements inside your anonymous function. It can use if-statements and loops. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.


Key points

  • A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
  • No unsafe code can be accessed within the anonymous-method-block.
  • Anonymous methods are not allowed on the left side of the is operator.
  • We use anonymous method in event handling.
  • An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
  • Unsafe code can’t be accessed within an anonymous method.
  • An anonymous method can’t access the ref or out parameters of an outer scope.
  • An anonymous method cannot access the ref or out parameters of an outer scope.

Syntax

 

// Create a delegate.
delegate int process_delegate(int num1, int num2);

// Instantiate the delegate using an anonymous method.
MyDel md = delegate(int num1, int num2) { /* do something */ };

The scope of the parameters of an anonymous method is the anonymous-method-block.

Example:

using System;

delegate void process_delegate(int num1, int num2);
namespace C#DelegatesDemo
{
    class delegate_program
    {
        static int num = 0 ;
        public static void AddNum(int p, int q)
        {
            num = p + q;
            Console.WriteLine("AddNum value: {0}", num);
        }

        public static void MultNum(int p, int q)
        {
            num = p * q;
            Console.WriteLine("MultNum value: {0}", num);
        }

        static void Main(string[] args)
        {
            //create delegate instances using anonymous method
           process_delegate pd = delegate(int x, int y)
            {
               Console.WriteLine("Anonymous Method: {0}{1}", x,y);
            };

            //calling the delegate using the anonymous method
            pd(20,10);

            //instantiating the delegate using the named methods
            pd =  new process_delegate(AddNum);

            //calling the delegate using the named methods
            pd(10,30);

            //instantiating the delegate using another named methods
            pd =  new process_delegate(MultNum);

            //calling the delegate using the named methods
            pd(5,10);
            Console.Read();
        }
    }
}

When the above code is compiled and executed, it produces the following result:
O/P:-

Anonymous Method:2010
AddNum value:40
MultNum value:50

out put

Anonymous Method as an Event Handler

You can use anonymous method on event handler. take simple example for button click event.

example:-

	// Click Event handler using Anonymous method
	 btnSubmit.Click+=delegate {
                                     MessageBox.Show("you clicked me");
                                    };

It will show the alert message when btnSubmit click event will occur.

One thought on “Anonymous method in C#

  1. Your article was good for anybody who wanted to learn the topic, but at the same time it wasted time as most of the things are repeated like any other article. Your title was advantage of anonymous method. But there was no mention of such thing. same rotten old stuff.

Leave a comment