This article discusses the basics of anonymous methods in C# and how to take advantage of them by implementing them in your applications.
An anonymous method is a block of code that is used as the parameter for the Delegate.
Anonymous method allows coder to pass block of code rather than the name of the method. Creating a anonymous method is a way to pass a code block as delegate parameter.
Benefits:
- To reduce code the amount of code
- To reduce complexity of code.
- To increase readability of code.
- Anonymous method can use any local variable declared outside of method.
Rules
- Cannot have jump statement that targets outside the anonymous method.
- Jump statement from outside of anonymous method cannot target inside anonymous method.
- Anonymous method cannot use Ref and Out parameter from outside of anonymous method.
Synatx:
Button1.Click+= delegate(Object o, EventArgs e)
{
MessageBox.Show("SCOTT");
}
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
// Decelaring Delegate
public delegate void Display(String msg);
static void Main(string[] args)
{
// Delegate using anonymous method
Display del = delegate(string par)
Display del = delegate(string par)
{
Console.WriteLine("{0}", par);
};
// Invoking delegate
del("Christ");
Console.ReadLine();
}
}
}
In above code, Christ will get display as output. In above code, block of code is getting passes as argument of delegate rather than name of the method.
Scope of the variable
The scope of variable of an anonymous method is the anonymous method block.
Anonymous method does not help speeding up the execution process because for block of code, .Net generates the Anonymous name.