So I have code like this:
int totalRequestsToSend = 0;
i = 1;
foreach (file in files)
{
try
{
// This can throw if adding request fails for some reason, e.g. file does not exist
requests.AddRequest(
new FileStoreRequest(file)
{
OnStoreConfirm = (file) =>
{
progress.Report((i*100)/totalRequestsToSend)
Interlocked.Increment(ref i);
}
}
);
totalRequestsToSend += 1;
}
catch(Exception e) {
// handle exception
}
}
Resharper complains with "access to modified closure" about line where I use totalRequestsToSend inside the lambda.
The logic works as expected and complaint could be ignored, however, one of Resharper's suggested fixes changes the int variable to an array of size 1 like so:
int[] totalRequestsToSend = {0};
i = 1;
foreach (file in files)
{
try
{
requests.AddRequest(
new FileStoreRequest(file)
{
OnStoreConfirm = (file) =>
{
progress.Report((i*100)/totalRequestsToSend[0])
Interlocked.Increment(ref i);
}
}
);
totalRequestsToSend[0] += 1;
}
catch(Exception e) {
// handle exception
}
}
This does not cause complaints from Resharper. I am puzzled. How is using an array different from using a variable in this case?
Thanks.