modified closure warning in ReSharper

Posted by Sarah Vessels on Stack Overflow See other posts from Stack Overflow or by Sarah Vessels
Published on 2010-06-01T15:27:56Z Indexed on 2010/06/01 15:33 UTC
Read the original article Hit count: 181

Filed under:
|
|
|

I was hoping someone could explain to me what bad thing could happen in this code, which causes ReSharper to give an 'Access to modified closure' warning:

bool result = true;

foreach (string key in keys.TakeWhile(key => result))
{
    result = result && ContainsKey(key);
}

return result;

Even if the code above seems safe, what bad things could happen in other 'modified closure' instances? I often see this warning as a result of using LINQ queries, and I tend to ignore it because I don't know what could go wrong. ReSharper tries to fix the problem by making a second variable that seems pointless to me, e.g. it changes the foreach line above to:

bool result1 = result;
foreach (string key in keys.TakeWhile(key => result1))

Update: on a side note, apparently that whole chunk of code can be converted to the following statement, which causes no modified closure warnings:

return keys.Aggregate(
    true,
    (current, key) => current && ContainsKey(key)
);

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET