As far as I understand, in the resharper suggestion " Implicitly captured closure: this", this
refers to the instance of HomeController
class. The question is now why did the following solutions worked to fix the problem and removed the Resharper suggestion.
public class HomeController : Controller
{
private ExcelDocument _excelDoc = new ExcelDocument();
private IDatabase _database = new CoreDatabase();
[HttpPost]
public JsonResult Insert(HttpPostedFileBase file, int programId)
{
_excelDoc.ReadData(firstDataRowIdx: 1, headerRowIdx: 0, excelFile: file);
_excelDoc.CompareToDatabaseCodes(_database.
.GetCodesWhere(c => c.ProgramID == programId && c.Active)// In this lambda Resharper says: 'Implicitly captured closure: this'
.Select(rc => rc.Code)
.ToList());
_excelDoc.InsertTireIds(_database
.GetTiersWhere(t => t.ProgramID == programId && _excelDoc.DistinctTiers.Contains(t.Tier)));
//More code...
}
}
I've found two ways to remove the Resharper suggestion without really understanding the reason behind those fixes.
Assign programId parameter to local variable like this:
[HttpPost] public JsonResult Insert(HttpPostedFileBase file, int programId) { _excelDoc.ReadData(firstDataRowIdx: 1, headerRowIdx: 0, excelFile: file); // Fix int selectedProgramId = programId; _excelDoc.CompareToDatabaseCodes(_database. .GetCodesWhere(c => c.ProgramID == selectedProgramId && c.Active)// In this lambda Resharper says: 'Implicitly captured closure: this' .Select(rc => rc.Code) .ToList()); _excelDoc.InsertTireIds(_database .GetTiersWhere(t => t.ProgramID == selectedProgramId && _excelDoc.DistinctTiers.Contains(t.Tier))); //More code... }
Assign _excelDoc.DistinctTiers (in second lambda) to a local variable:
[HttpPost] public JsonResult Insert(HttpPostedFileBase file, int programId) { _excelDoc.ReadData(firstDataRowIdx: 1, headerRowIdx: 0, excelFile: file); _excelDoc.CompareToDatabaseCodes(_database. .GetCodesWhere(c => c.ProgramID == programId && c.Active)// In this lambda Resharper says: 'Implicitly captured closure: this' .Select(rc => rc.Code) .ToList()); // Fix List<int> distinctTiers = _excelDoc.DistinctTiers; _excelDoc.InsertTireIds(_database .GetTiersWhere(t => t.ProgramID == programId && distinctTiers.Contains(t.Tier))); //More code... }
Please help me understand why my fixes worked.
Let me know if more info is required to explain the problem better.
Thanks!!!