Basically anonymous methods are
methods without a name, but only the body. These methods are useful when you
want to declare a method that is doing simple work. It came
with C# 2.0 as a solution to declare a _delegate_ without the need of a separate
named method. The syntax for such a declaration is as follows.
public class Program
{
public delegate void DelegateType();
static void Main(string[] args)
{
DelegateType DelegateObject = delegate()
{
Console.WriteLine("AnonymousMethod
is invoked");
};
DelegateObject();
Console.ReadKey();
}
}
Note that you can write anonymous
methods of any return type and parameters.
public class Program
{
public delegate int DelegateType(int x);
static void Main(string[] args)
{
DelegateType DelegateObject = delegate(int x)
{
return x;
};
int result = DelegateObject(5);
Console.WriteLine("Result is :
{0}", result);
Console.ReadKey();
}
}
Though we define an anonymous
method one time we can reuse it because we are wrapping it in a delegate.
Anonymous methods can be useful in a situation when we find
a named method is an unnecessary overhead. A good example would be when you
start a new thread. Look at the following example.
public class Program
{
public delegate void DelegateType();
static void Main(string[] args)
{
System.Threading.Thread thread = new System.Threading.Thread
(delegate()
{
System.Console.Write("This Thread is performing work");
});
thread.Start();
Console.ReadKey();
}
}