See the code
public class Test
{
public static void Main()
{
Test t = new Test();
var AnonymousMethod = t.OuterMethod();
AnonymousMethod("passedValue");
}
public delegate void SampleDelegate(string InputText);
public SampleDelegate OuterMethod()
{
string outerValue="outerValue";
return (x => {
Console.WriteLine(x);
Console.WriteLine(outerValue);
});
}
}
OutPut
Success time: 0.02 memory: 33816 signal:0
passedValue
outerValue
Link to Example
Normally the scope of variable outerValue
would end after calling t.OuterMethod()
. But in the case of using anonymous type, Console printed the output clearly (Console.WriteLine(outerValue)
) which means the scope of variable didn't end. What do actually the compiler do to determine its scope? Will it assign the scope of Main
method to the variables used inside the anonymous method? I know how to use but don't know how it works. Please guide me?
Edit
Suppose the anonymous method attached to an event. The event might be executing a lot later. Then the variable would be in memory. rite? If a lot of events assigned, a lot of memory!. Its a bad thing I suppose. Did I make any mistake?