class Program {
static void Main(string[] args) {
Fn f = Add; // Fn f = new Fn(Add);
Console.WriteLine(f(20, 30));
}
static int Add(int a, int b) {
return a + b;
}
delegate int Fn(int a, int b);
}
The same can be written using anonymous methods (introduced in c# 2.0) as
class Program {
static void Main(string[] args) {
Fn f1 = delegate(int a, int b) {
return a + b;
};
Console.WriteLine(f1(50, 60));
}
static int Add(int a, int b) {
return a + b;
}
delegate int Fn(int a, int b);
}
The advantages of using anonymous methods is
1. Elegant and clean code.
2. The place where anonymous methods come handy is that it includes capability of capturing local state. The local variables and parameters whose scope contain an anonymous method declaration are called outer or captured variables of the anonymous method. For example, in the following code segment, n is an outer variable:
int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };
3. Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. A reference to n is captured at the time the delegate is created.
4. An anonymous method cannot access the ref or out parameters of an outer scope.
Another example
List
list.Sort(delegate(int a, int b) { return a - b; });
No comments:
Post a Comment