top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of Anonymous Methods in C#?

0 votes
365 views
What is the use of Anonymous Methods in C#?
posted May 28, 2014 by Atul Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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

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

Syntax for Writing an Anonymous Method

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);
answer Jun 24, 2014 by Amit Kumar Pandey
...