1.

What are Anonymous Methods in C#?

Answer»

A method without a name is Anonymous Method. It is defined USING the delegate keyword.

The Anonymous methods can be assigned to a variable of delegate type. It can also be passed as a parameter. Here are some of the features of Anonymous Methods in C#:

  • Anonymous methods are defined using the delegate keyword.
  • Anonymous methods can be used in event handling.
  • Any unsafe CODES cannot be accessed inside anonymous methods.
  • Variables declared outside the anonymous methods can be accessed inside them.
  • Variables declared inside the anonymous methods cannot be accessed outside them.
  • Anonymous methods can be passed as parameters.

The following is an example:

using System; public delegate void DemoDelegate(int value); public CLASS Example {   public STATIC void Display(DemoDelegate one,int a)    {        a *= 50;        one(a);    }    public static void Main(string[] args)    {        Display(delegate(int a) { Console.WriteLine("Anonymous method = {0}", a); }, 100);    } }

The output: 

Anonymous method = 5000

Let US see another example: 

using System; namespace AnonymousMethodDemo {   class Example {      public delegate void sum(int x, int y);      static void Main(string[] args)      {         sum s = delegate(int x, int y)         {           Console.WriteLine("Inside Anonymous method");           Console.WriteLine("Sum = {0}",x + y);         };         s(7, 12);      }   } }

The output of the above program is as follows:

Inside Anonymous method Sum = 19


Discussion

No Comment Found