So, this one is pretty straight forward I think.
Here is my code:
Dictionary<int, IEnumerable<SelectListItem>> fileTypeListDict = new Dictionary<int, IEnumerable<SelectListItem>>();
foreach (PresentationFile pf in speakerAssignment.FKPresentation.PresentationFiles)
{
IEnumerable<SelectListItem> fileTypes = Enum.GetValues(typeof(PresentationFileType))
.Cast<PresentationFileType>().Select(x => new SelectListItem
{
Text = x.ToString(),
Value = Convert.ToString((int)x),
Selected = pf.Type == (int)x
});
fileTypeListDict.Add(pf.ID, fileTypes);
}
What is happening is that in the end the dictionary will have all the correct keys, but all of the values will be set to the fileTypes list created during the final iteration of the loop. I am sure this has something to do with the object being used as a reference, but have not seen this issue before in my time with C#. Anyone care to explain why this is happening and how I should resolve this issue?
Thanks!
This is the infamous “
foreachcapture issue”, and is “fixed” in C# 5 (“fixed” is a strong word, since it suggests it was a “bug” before: in reality – the specification is now changed to acknowledge this as a common cause of confusion). In both cases, the lambda captures the variablepf, not “the value ofpfduring this iteration” – but in C# before-5 the variablepfis technically scoped outside the loop (so there is only one of them, period), where-as in C# 5 and above the variable is scoped inside the loop (so there is a different variable, for capture purposes, per iteration).In C# 4, just cheat:
now
pfis scoped inside theforeach, and it will work OK. Without that, there is only onepf– and since you’ve deferred execution until the end, the value of the singlepfwill be the last iteration.An alternative fix would be: don’t defer execution:
Now it is evaluated while the
pfis “current”, so will have the results you expected.