1

This loop is executed

CoordPosition = new Func<string, int>[3];
for (int i = 0; i < CoordPosition.Length; i++)
{
     CoordPosition[i] = (x => CapStringNumber(x, i));
}

When the method CapStringNumber is later executed by the funcs its second parameter has the value 3 for the entire array. I want it to be 0, 1, 2.

The following works:

CoordPosition = new Func<string, int>[3];
for (int i = 0; i < CoordPosition.Length; i++)
{
     var localVariable = i; 
     CoordPosition[i] = (x => CapStringNumber(x, localVariable));
}

What is the proper way to achieve the effect I want? Making that localVariable seems a bit un-maintainable. I don't know javaScript but i'm told that 'IIFE' is a relevant javaScript term for this.

Adam
  • 2,845
  • 2
  • 32
  • 46
  • Your second sample is a proper way. _Making that localVariable seems a bit un-maintainable_ - in which way it is unmaintainable? – Fabio Apr 13 '17 at 09:24
  • 2
    I recommend [this](http://www.codethinked.com/c-closures-explained) and [this](http://csharpindepth.com/Articles/Chapter5/Closures.aspx) to find out more about Closures. – wkl Apr 13 '17 at 09:27
  • 1
    I meant unmaintainable in the way that it looks like a unnecessary variable, which could be refactored by mistake. Coupled with a comment it would be safer ofcourse – Adam Apr 13 '17 at 09:30
  • 2
    Copying the variable inside your closure seems the way to go. [Captured variable in a loop in C#](http://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp) (Jon Skeet surely knows best!). – Georg Patscheider Apr 13 '17 at 09:36
  • FYI you can omit the `(...)`: ` = x => CapStringNumber(...)`; – xanatos Apr 13 '17 at 09:36
  • 1
    Possible duplicate of [Captured variable in a loop in C#](http://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp) – wkl Apr 13 '17 at 09:37
  • And no, IIFE is totally different (you can see what it is if you look at the description of the tag) – xanatos Apr 13 '17 at 09:37

0 Answers0