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.
C# 2.0 provides a new feature called Anonymous Methods, which allow you to create inline un-named ( i.e. anonymous ) methods in your code, which can help increase the readability and maintainability of your applications by keeping the caller of the method and the method itself as close to one another as possible.
Anonymous methods are a new feature in C# 2.0 that allow you to hook an action directly to an event as opposed to having a separate event handler. For example, when a user clicks a button and you need to pop-up a MessageBox, you could handle it the standard way with a delegate and an event handler, or you could hook the action to perform directly to the Click event using an anonymous method as shown next:
{
Button1.Click += delegate
{
Response.Write(“Thanks for clicking the button!”);
};
}
Looking through the code you’ll see that no method name is given to the inline event handler method. Instead it uses the delegate keyword and defines the parameters that the event handler would normally expect.
Anonymous methods can be specified with parameters enclosed in parenthesis, or without parameters, with empty parenthesis. When parameters are specified, the signature of the anonymous method must match the signature of the delegate. When the delegate has no parameters, empty parenthesis are specified in the anonymous method declaration. When an anonymous method is declared without parenthesis, it can be assigned to a delegate with any signature.
Note that method attributes cannot be applied to Anonymous methods. Also, anonymous methods can be added to the invocation list for delegates but can be deleted from the invocation list only if they have been saved to delegates.
An advantage offered with the use of anonymous methods is that they allow access to the local state of the containing function member.
Conclusion
Anonymous methods offer a simple and elegant solution in many situations. In the next version of C#, (C# 3.0), anonymous methods are evolved into Lambda Expressions used in Language Integrated Query (Linq).
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.
Example: Open a console application
List<Customer> custs = new List<Customer>();
Customer cust1 = new Customer();
cust1.Age = 35;
cust1.Name = “John Doe”;
cust1.CustomerSince = new DateTime(2000, 1, 1);
Customer cust2 = new Customer();
cust2.Age = 33;
cust2.Name = “Jamie Doe”;
cust2.CustomerSince = new DateTime(2006, 4, 1);
Customer cust3 = new Customer();
cust3.Age = 10;
cust3.Name = “Jane Doe”;
cust3.CustomerSince = new DateTime(1999, 2, 1);
custs.Add(cust1);
custs.Add(cust2);
custs.Add(cust3);
Console.WriteLine(“Sorting by CustomerSince date:”);
custs.Sort(delegate(Customer c1, Customer c2)
{
return Comparer<DateTime>.Default.Compare(c1.CustomerSince,
c2.CustomerSince);
});
foreach (Customer cust in custs)
{
Console.WriteLine(cust.Name + ” ” +
cust.CustomerSince.ToShortDateString());
}
Console.WriteLine(“\r\nSorting by Age:”);
custs.Sort(delegate(Customer c1, Customer c2)
{
return Comparer<int>.Default.Compare(c1.Age, c2.Age);
});
foreach (Customer cust in custs)
{
Console.WriteLine(cust.Name + ” ” + cust.Age.ToString());
}
or:
custs.ForEach(delegate(Customer cust)
{
Console.WriteLine(cust.Name + ” ” + cust.Age.ToString());
});
Console.Read();
}
}
public class Customer
{
private DateTime _CustomerSince;
private int _Age;
private string _Name;
public DateTime CustomerSince
{
get { return _CustomerSince; }
set { _CustomerSince = value; }
}
public int Age
{
get { return _Age; }
set { _Age = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
EXAMPLE:
Here is a simple example of using an anonymous method to find all the even integers from 1…10:
private int[] _integers =
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers,
delegate(int integer)
{
return (integer%2 == 0);
}
);
The Anonymous Method is:
delegate(int integer)
{
return (integer%2 == 0);
}
which is called for each integer in the array and returns either true or false depending on if the integer is even.
If you don’t use an anonymous method, you will need to create a separate method as such:
private int[] _integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] evenIntegers = Array.FindAll(_integers, IsEven);
private bool IsEven(int integer)
{
return (integer%2 == 0);
}
When you have very simple methods like above that won’t be reused, I find it much more elegant and meaningful to use anonymous methods. The code stays closer together which makes it easier to follow and maintain.
Here is an example that uses an anonymous method to get the list of cities in a state selected in a DropDownList ( called States ):
List<City> citiesInFlorida =
cities.FindAll(delegate(City city)
{
return city.State.Name.Equals(States.SelectedValue);
}
);
You can also use anonymous methods as such:
button1.Click +=
delegate
{
MessageBox.Show("Hello");
};
which for such a simple operation doesn’t “deserve“ a separate method to handle the event.
Other uses of anonymous methods would be for asynchronous callback methods, etc.
Anonymous methods don’t have the cool factor of Generics, but they do offer a more expressive in-line approach to creating methods that can make your code easier to follow and maintain.