0

I think I lack the proper words to google the answer to this topic, so if anyone wouldnt mind giving me a quick run down on how this works:

I got a two dimensional List of buttons and a two dimensional list of arbitrary objects of a Class A. When a button is pressed, I want it to call a function that receives the corresponding object of Type A. I run into an out of bounds error though, probably because the List of A is out of scope (while it still does exist, but seemingly not in the scope of the lambda).

What would best practice look like in such a case? When are the variables used in a lambda expression evaluated? Can I make them behave like smart pointers?

public void loadWorld(World w) {
    for (int i = 0; i < w.ListOfA.Count; i++) {

        for (int j = 0; j < w.ListOfA[i].Count; j++)
        {
            Button btn = new Button();
            
            btn.Pressed += (s, e) => handleVisit(w.ListOfA[i][j]);
        }
    }
}
EKOlog
  • 410
  • 7
  • 19
Patsch
  • 1
  • 1
  • https://stackoverflow.com/q/451779/5311735 < should explain. – Evk Oct 27 '21 at 13:01
  • JetBrains has a good explanation of "Access to modified captured variable": https://www.jetbrains.com/help/resharper/2021.2/AccessToModifiedClosure.html – Yevhen Cherkes Oct 27 '21 at 13:04

0 Answers0