My code is like this:
Dictionary<string, string> specialCharacters = new Dictionary<string, string>();
specialCharacters.Add("@", "%");
specialCharacters.Add("*", "^");
List<Action<Employee>> listOfDel = new List<Action<Employee>>();
foreach (KeyValuePair<string, string> character in specialCharacters)
{
Action<Employee> replace = (empData) => empData.EmpName = empData.EmpName.ToString().Replace(character.Key, character.Value);
listOfDel.Add(replace);
//listOfDel.Add(new Action<Employee>((empData) => empData.EmpName = empData.EmpName.ToString().Replace(character.Key, character.Value)));
}
The issue is the list listOfDel has the same action as it refers to same function replace which takes value of last pair of character.Key, character.Value ((““, “^”)
I want a result having different actions in the list of actions listOfDel , where each method will have different value present. (“@”, “%”), (““, “^”);
I also tried creating a new instance of action delegate and using it as anonymous method.Please see commented code, yet the problem is not solved.
The problem is that you’re capturing the iterator variable. There’s only one variable declared by the
foreachloop, so by the time you execute the delegates, they’ll all be using the same value (they all refer to the same delegate). For C# 4 and earlier, you just need to create a copy:C# 5 will render this unnecessary, as
foreachwill be fixed so that each iteration will have a separate variable as far as anonymous functions are concerned.See Eric Lippert’s blog post “Closing over the loop variable considered harmful” for more information.