c# - Anonymous delegates in a foreach loop -
possible duplicate:
question foreach , delegates
i know phenomenon going on here:
converting list<string> list of delegates returning same string goes wrong.
this happens in wrongconversion when work directly variable returned foreach on input list. (the last string in list returned each time)
in correctconversion, first assign local variable , use in delegate.
this assignment seems superfluous @ first.
input:
using system.collections.generic; class program { delegate string stringreturner(); static void main(string[] args) { var list = new list<string> { "a", "b", "c" }; display(wrongconversion(list)); display(correctconversion(list)); system.console.readkey(); } static list<stringreturner> wrongconversion(list<string> list) { var result = new list<stringreturner>(); foreach (var s in list) { result.add(() => { return s; }); // <========= s "c" ? } return result; } static list<stringreturner> correctconversion(list<string> list) { var result = new list<stringreturner>(); foreach (var s in list) { var localstring = s; // <========= happens here? result.add(() => { return localstring; }); } return result; } private static void display(list<stringreturner> list) { foreach (var stringreturner in list) system.console.write(stringreturner()); system.console.writeline(); } } output:
ccc abc
this known "bug" in c# (vb.net think). simple answer localstring variable create scoped inside foreach, therefore new copy of used each itteration, in other case reference s, ends beeing c (before print @ least). "resolve" issues of kind i've made practice do
foreach(var _s = ....) { var s = _s; /* code here uses s */ } every time have use delegates that.
Comments
Post a Comment