0

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.

Corvin
  • 990
  • 11
  • 17
  • 1
    look at the answer [here](http://stackoverflow.com/questions/1688465/resharper-warning-access-to-modified-closure) – Jonesopolis Dec 08 '16 at 19:39
  • @Jonesopolis That doesn't say anything about the closed over variable being wrapped in an array, or why resharper would suggest such a refactor. Note of course that the access to a modified closure is *desired* in this case; it's not an unintentional usage of it. – Servy Dec 08 '16 at 20:00
  • @Servy I sure did something to piss you off. I can't even provide a link that might add some context without you jumping all over me anymore. It's a comment in an attempt to help. – Jonesopolis Dec 08 '16 at 20:08
  • @Jonesopolis, thanks. This does not exactly address my question, but it does reinforce me in believing that this suggestion is broken in Resharper – Corvin Dec 10 '16 at 00:39

1 Answers1

0

It's not any different. The refactor accomplishes nothing productive.

Servy
  • 202,030
  • 26
  • 332
  • 449