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.
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
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:will display the size of the list, because on each iteration you're incrementing
count
.However, the call to
SomeFunction
passes the evaluated value ofcount++
(which is the value ofcount
before the increment) by value toSomeFunction
. In other words,SomeFunction
can't change the value ofcount
.For more on closures and variable capture, see my closures article.
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.