Does C# Pass by Value to Lambdas?

2019-06-22 05:46发布

I have some code,

int count = 0;

list.ForEach(i => i.SomeFunction(count++));

This seems to not increment count. Is count passed by value here? Is there any difference if I use the {} in the lambda?

int count = 0;

list.ForEach(i => 
            {
                    i.SomeFunction(count++);
            });

Update 1

Sorry, my mistake, it does update the original count.

9条回答
等我变得足够好
2楼-- · 2019-06-22 06:24

I wanted to add a small correction here. The variable count is neither passed by value or by reference to the lambda expression because it is not a parameter. The value is instead captured by the lambda in a closure.

You should check out Raymond's series on the subject - http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx

查看更多
SAY GOODBYE
3楼-- · 2019-06-22 06:26

The variable count is captured by the lambda expression in your situation. Any changes to count will be visible to the caller. So, for instance:

int count = 0;
list.ForEach(i => i.SomeFunction(count++));
Console.WriteLine(count);

will display the size of the list, because on each iteration you're incrementing count.

However, the call to SomeFunction passes the evaluated value of count++ (which is the value of count before the increment) by value to SomeFunction. In other words, SomeFunction can't change the value of count.

For more on closures and variable capture, see my closures article.

查看更多
我命由我不由天
4楼-- · 2019-06-22 06:26

No, there is no difference. Arguments are usually by value, unless you explicitly make it "ref" or "out" in the delegate definition used for the lambda.

查看更多
登录 后发表回答