Recently, I read C # in Depth, and he taught me lambda expression, I used them for pas data for event clicks, etc., for example:
image.MouseDown+=(o ,e)=>MethodToDoSomething(DataNeededForAction);
Now the problem with these variables is captured when used in the foreach loop (thanks to Jon Skeet for the fact that this part is really understandable :), when initializing several objects that have events that I sign, I usually encounter a problem with the catch variable. consider the following example:
foreach (var game in GamesCollection) { Image img = new Image(); img.Width = 100; img.MouseDown+=(o,e) => MyMethod(game.id); }
In order to avoid capture in this situation, I have to add some variable to assign the game, and then pass this variable to the method, which creates extra fuzzy code and basically an extra mess. Is there any way around this? Something that at least looks cleaner?
thanks ziv
source share