0
votes

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.

1
look at the answer hereJonesopolis
@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
@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
@Jonesopolis, thanks. This does not exactly address my question, but it does reinforce me in believing that this suggestion is broken in ResharperCorvin

1 Answers

0
votes

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