code_junkie

C# Captured Variable In Loop

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. List<Func<int>> actions = new List<Func<int>>();
  2.  
  3. int variable = 0;
  4. while (variable < 5)
  5. {
  6. actions.Add(() => variable * 2);
  7. ++ variable;
  8. }
  9.  
  10. foreach (var act in actions)
  11. {
  12. Console.WriteLine(act.Invoke());
  13. }
  14.  
  15. while (variable < 5)
  16. {
  17. int copy = variable;
  18. actions.Add(() => copy * 2);
  19. ++ variable;
  20. }
  21.  
  22. for (int i=0; i < 10; i++) // Just one variable
  23. foreach (string x in foo) // And again, despite how it reads out loud
  24.  
  25. List<Func<int>> actions = new List<Func<int>>();
  26.  
  27. int variable = 0;
  28. while (variable < 5)
  29. {
  30. int variable1 = variable;
  31. actions.Add(() => variable1 * 2);
  32. ++variable;
  33. }
  34.  
  35. foreach (var act in actions)
  36. {
  37. Console.WriteLine(act.Invoke());
  38. }
  39.  
  40. Console.ReadLine();
  41.  
  42. while( variable < 5 )
  43. {
  44. int copy = variable;
  45. actions.Add( () => copy * 2 );
  46. ++variable;
  47. }
  48.  
  49. for (int counter = 1; counter <= 5; counter++)
  50.  
  51. {
  52.  
  53. new Thread (() => Console.Write (counter)).Start();
  54.  
  55. }
  56.  
  57. for (int counter = 1; counter <= 5; counter++)
  58.  
  59. {
  60.  
  61. int localVar= counter;
  62.  
  63. new Thread (() => Console.Write (localVar)).Start();
  64.  
  65. }
Add Comment
Please, Sign In to add comment