Search code examples
c#anonymous-functionanonymous-methods

Where does anonymous function body variables saved ?


Below code is working but why ? Where does the x and y coming/saved when I invoke anonymous method in the loop.

thanks

    static void Main(string[] args)
    {
        int x=1;
        int y=2;
        var dic = GetDic(x, y);

        for (int i = 0; i < 5;i++ )
        {
            System.Console.WriteLine(dic[i].Invoke().ToString());
        }

    }

    private static Dictionary<int, Func<int>> GetDic(int x, int y)
    {
        var dic = new Dictionary<int, Func<int>>()
        {
            {0,()=>{return y;}},
            {1,()=>{return x;}},
            {2,()=>{return x+y;}},
            {3,()=>{return x-y;}},
            {4,()=>{return y-x;}},
        };
        return dic;
    }

Solution

  • Lambda expressions are compiled into separate methods. If they don't use local variables from the surrounding code, they are compiled into methods of the same class. However, when local variables are used (like in this case), the compiler creates a nested class in the surrounding type and puts the compiled method and fields matching the used local variables there. When the lambda expression is used, an instance of that class is created and the values are stored in instance fields so the lambda method has access to them.

    This also implies that using local variables from the surrounding method in a lambda expression is slightly more expensive than a lambda expression that only uses its parameters and static members of other types.