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.
A block scoped variable should resolve the warning.
@foreach(var item in Model)
{
    var myItem = item;
    <div>@Html.DisplayBooleanFor(modelItem => myItem.BooleanField)</div>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With