views:

8360

answers:

1
    string [] files = new string[2];
    files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml";
    files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml";

    //Resharper complains this is an "access to modified closure"
    for (int i = 0; i < files.Length; i++ )
    {
        // Resharper disable AccessToModifiedClosure
        if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(),
        delegate(string name) { return name.Equals(files[i]); }))
             return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]);
        // ReSharper restore AccessToModifiedClosure
    }

The above seems to work fine though resharper complains that this is "access to modified closure". Can any one shed light on this?

Thanks in advance.

(this topic continued here)

+59  A: 

In this case, it's okay, since you are actually executing the delegate within the loop.

If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the variable i rather than its value at the time of the delegates creation.

In short, it's something to be aware of as a potential trap, but in this case it doesn't hurt you.

See the bottom of this page for a more complex example where the results are counterintuitive.

Jon Skeet
Thanks Jon, that helped! :)
Vyas Bharghava
could you comment on this -> http://stackoverflow.com/questions/304258/access-to-modified-closure-2
faulty
@faulty: Marc's said everything I want to say :)
Jon Skeet