Suppose we have a method which returns a delegate that references an anonymous method that uses some of the local variables in its enclosing method. Surely local variables only live as long as the method that is calling them is executing, and thus the variable referred to by the anonymous method will no longer exist? In fact, this is not the case. Actually, the anonymous method would “capture” the local variables that it uses from its enclosing method. In such a case, when the delegate is called; it would remember the state of local variables as they were when the enclosing method was called. This process is known as taking a “closure”. You can think of a closure as a set of data attached to a function.
Depicted here is a class ArithmeticOperationBuilder; which has a method called Ev (in the line of short form of “Evaluate”); which takes two parameters and a char indicating the arithmetic operation to be performed on the two parameters. The method returns a delegate of the type Operation which takes no parameter and returns an int. The delegate references an anonymous method which uses the copy of the parameters passed to method inside its body. When we use the delegate returned from the method, it would capture what values were passed. Note that the delegate itself does not take any parameter.
using System;
namespace ClassLibrary { public delegate int Operation(); public class ArithmeticOperationBuilder { public static Operation Ev(int param1, int param2, char op) { int op1 = param1; int op2 = param2; Operation operation = delegate() { switch (op) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: //default operation is addition return op1 + op2; } }; return operation; } } }
For example; the following would give an output of 3:
Operation o = Ev(1, 2, '+'); Console.WriteLine(o());
The delegate o has remembered the values of arguments passed to it while creating it. If you want to do some really “complex” arithmetic using the function Ev here’s a sample:
int val = Ev(Ev(Ev(1, 2, '+')(), 3, '+')(), 2, '*')();
This is nothing but the naïve arithmetic expression: (1 + 2 + 3) * 2 which equals to12 !
|
No responses found. Be the first to respond and make money from revenue sharing program.
|