26

I'm getting this ReSharper warning: Access to foreach variable in closure. May have different behaviour when compiled with different versions of compiler.

This is what I'm doing:

@foreach(var item in Model)
{
    // Warning underlines "item".
    <div>@Html.DisplayBooleanFor(modelItem => item.BooleanField)</div>
}

My extension is as follows:

public static MvcHtmlString DisplayBooleanFor<TModel, TValue>(
    this HtmlHelper<TModel> helper, 
    Expression<Func<TModel, TValue>> expression)
{
    bool value;

    try
    {
        var compiled = expression.Compile()(helper.ViewData.Model);
        value = Convert.ToBoolean(compiled);
    }
    catch (Exception)
    {
        value = false;
    }

    return MvcHtmlString.Create(value ? "Yes" : "No");
}

Note this is working as expected but how can I avoid this warning?
I'll appreciate any help provided.

Esteban
  • 3,108
  • 3
  • 32
  • 51

2 Answers2

25

A block scoped variable should resolve the warning.

@foreach(var item in Model)
{
    var myItem = item;
    <div>@Html.DisplayBooleanFor(modelItem => myItem.BooleanField)</div>
}
ChaosPandion
  • 77,506
  • 18
  • 119
  • 157
  • 1
    Thank you, it fixed the warning, any idea why this happens? – Esteban Sep 22 '12 at 20:10
  • 10
    @Esteban there's more on the JetBrains wiki [here](http://confluence.jetbrains.net/display/ReSharper/Access+to+modified+closure) (which depending on your version of R# may be linked directly from the lightbulb menu as 'Why is ReSharper suggesting this?); see also [this SO question](http://stackoverflow.com/questions/235455/access-to-modified-closure?rq=1) – AakashM Sep 24 '12 at 08:17
  • 2
    @Esteban That's the best explication I found so far : http://stackoverflow.com/questions/14907987/access-to-foreach-variable-in-closure – ForceMagic Feb 12 '14 at 15:19
2

Another option is to apply JetBrains.Annotations.InstantHandleAttribute attribute to DisplayBooleanFor method.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Ivan
  • 21
  • 1