Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# Pass by Value to Lambdas?

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.

like image 206
Anthony D Avatar asked May 12 '09 13:05

Anthony D


People also ask

Does hep C go away?

Overview. Hepatitis C virus (HCV) causes both acute and chronic infection. Acute HCV infections are usually asymptomatic and most do not lead to a life-threatening disease. Around 30% (15–45%) of infected persons spontaneously clear the virus within 6 months of infection without any treatment.

What is the main cause of hep C?

Hepatitis C is a liver infection caused by the hepatitis C virus (HCV). Hepatitis C is spread through contact with blood from an infected person. Today, most people become infected with the hepatitis C virus by sharing needles or other equipment used to prepare and inject drugs.

How long can you have hep C without knowing?

Acute hepatitis C usually goes undiagnosed because it rarely causes symptoms. When signs and symptoms are present, they may include jaundice, along with fatigue, nausea, fever and muscle aches. Acute symptoms appear one to three months after exposure to the virus and last two weeks to three months.


1 Answers

count is an int, and ints are value types, which means they are indeed passed by value. There is no semantic difference between your first and second example.

(That said, it looks to me like it should be incrementing count, since it should be capturing the original reference as far as the closure. To clarify -- although count will be passed by value down into SomeFunction, things don't get "passed" into your lambda expression when you use them inside the expression -- they are the same reference as the external variable.)

like image 96
mqp Avatar answered Oct 17 '22 03:10

mqp