modified closure warning in ReSharper
- by Sarah Vessels
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)
);