Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

modified closure warning in ReSharper

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)
);
like image 234
Sarah Vessels Avatar asked Dec 01 '22 05:12

Sarah Vessels


1 Answers

In that particular code nothing, take the following as an example:

int myVal = 2;

var results = myDatabase.Table.Where(record => record.Value == myVal);

myVal = 3;

foreach( var myResult in results )
{
    // TODO: stuff
}

It looks like result will return all records where the Value is 2 because that's what myVal was set to when you declared the query. However, due to deferred execution it will actually be all records where the Value is 3 because the query isn't executed until you iterate over it.

In your example the value isn't being modified, but Resharper is warning you that it could be and that deferred execution could cause you problems.

like image 121
Dave D Avatar answered Dec 04 '22 21:12

Dave D