C# - Anonymous Methods



We discussed 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.

Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body.

Anonymous Method Declaration

An anonymous method is a special type of method which does not have any method name. The method is defined using the "delegate" keyword and it can be assigned to a delegate type variable.

You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.

Anonymous Method Declaration

Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword. For example,

delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x) {
   Console.WriteLine("Anonymous Method: {0}", x);
};

The code block Console.WriteLine("Anonymous Method: {0}", x); is the body of the anonymous method.

The delegate could be called both with anonymous methods as well as named methods in the same way, i.e., by passing the method parameters to the delegate object.

For example,

nc(10);

Example of Anonymous Method

The following example demonstrates the use of delegates, including both named methods and anonymous methods −

using System;
delegate void NumberChanger(int n);
namespace DelegateAppl {
   class TestDelegate {
      static int num = 10;
      
      public static void AddNum(int p) {
         num += p;
         Console.WriteLine("Named Method: {0}", num);
      }
      public static void MultNum(int q) {
         num *= q;
         Console.WriteLine("Named Method: {0}", num);
      }
      public static int getNum() {
         return num;
      }
      static void Main(string[] args) {
         //create delegate instances using anonymous method
         NumberChanger nc = delegate(int x) {
            Console.WriteLine("Anonymous Method: {0}", x);
         };
         
         //calling the delegate using the anonymous method 
         nc(10);
         
         //instantiating the delegate using the named methods 
         nc =  new NumberChanger(AddNum);
         
         //calling the delegate using the named methods 
         nc(5);
         
         //instantiating the delegate using another named methods 
         nc =  new NumberChanger(MultNum);
         
         //calling the delegate using the named methods 
         nc(2);
         Console.ReadKey();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

Anonymous Method: 10
Named Method: 15
Named Method: 30

Anonymous Methods with Built-in Delegates

You can use anonymous methods to define inline logic for built-in delegates such as Action, Func, and Predicate.

Example

The following example demonstrates how to use an anonymous method with the Action delegate:

using System;

class Program {
   static void Main(string[] args) {
      // Creating an Action delegate instance using an anonymous method
      Action<string> greet = delegate(string name) {
         Console.WriteLine("Hello, " + name + "!");
      };

      // Calling the delegate
      greet("Sudhir");

      Console.ReadKey();
   }
}

When the above code is compiled and executed, it produces the following result −

Hello, Sudhir!

Anonymous Method to a Lambda Expression

To create shorter syntax for inline methods, you can simplify anonymous methods by converting them to lambda expressions.

Example

The following example demonstrates how an anonymous method can be replaced by a lambda expression using the Action delegate:

using System;

class Program {
   static void Main(string[] args) {
      // Using an anonymous method
      Action<string> greet1 = delegate(string name) {
         Console.WriteLine("Anonymous Method: Hello, " + name + "!");
      };
      greet1("Prakash");

      // Using a lambda expression
      Action<string> greet2 = (name) => {
         Console.WriteLine("Lambda Expression: Hello, " + name + "!");
      };
      greet2("Sudhir");

      Console.ReadKey();
   }
}

When the above code is compiled and executed, it produces the following result −

Anonymous Method: Hello, Prakash!
Lambda Expression: Hello, Sudhir!
Advertisements