What are anonymous methods in C#?

CsharpProgrammingServer Side Programming

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

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

Example

 Live Demo

using System;
delegate void Demo(int n);
namespace DelegateAppl {
   class TestDelegate {
      static int num = 50;
      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
         Demo d = delegate(int x) {
            Console.WriteLine("Anonymous Method: {0}", x);
         };
         //calling the delegate using the anonymous method
         d(100);
         //instantiating the delegate using the named methods
         d = new Demo(AddNum);
         //calling the delegate using the named methods
         d(5);
         //instantiating the delegate using another named methods
         d = new Demo(MultNum);
         //calling the delegate using the named methods
         d(2);
         Console.ReadKey();
      }
   }
}

Output

Anonymous Method: 100
Named Method: 55
Named Method: 110

Above the following is our anonymous method.

Demo d = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
raja
Published on 18-Sep-2018 12:24:09
Advertisements