Why is method in lambda expression being executed

I have a simple test program and wondering why the console is outputting 1 instead of 6? Thank.

static void Main(string[] args)
    {
        var t = new List<int>() {1, 1, 1, 1, 1};
        var s = new List<int>() {1};

        var g = t.Select(a => test(a, s));
            Console.WriteLine(s[0]);    
    }

    private static int test(int a, List<int> s )
    {
        s[0]++;
        return a;
    }

      

+3


source to share


1 answer


IEnumerable is lazy . The expression is not evaluated until needed, so it is test

never called.

Add Console.WriteLine(g.ToList());

and you will see how the method is now called test

. You can force it to evaluate in your code using: var g = t.Select(a => test(a, s)).ToList();

This will cause the enum to be evaluated in the list.

See Lazy Evaluation :



In programming language theory, lazy or on-demand evaluation is an evaluation strategy that delays evaluation of an expression until its value is needed (loose evaluation) and also avoids re-evaluation (sharing).

Note. It is generally not recommended to use LINQ code that causes side effects, see 4th paragraph of this blog post .

+8


source







All Articles