Is Lambda code repetitive with dynamically generated controls?

I answered a question today , mainly about UI interaction. But later, it got me thinking about how the OP was using dynamically generated controls with their code.

Having skipped 2-4 on .Net and only now learning "new" things, it actually made me put the question in my fist ..:

private void AddPieceButton_Click(object sender, EventArgs e)
{
   somePieceControl newPiece = new somePieceControl ();
   //..
   newPiece.MouseDown += (sender2, evt) =>  { /* 1st block of code */ };
   newPiece.MouseUp   += (sender2, evt) =>  { /* 2nd block of code */ };
   newPiece.MouseMove += (sender2, evt) =>  { /* 3rd block of code */ }
   //..
   someContainer.Controls.Add(newPiece);
}

      

In the test case, the question hardly matters; but blocks of code can easily get much more, and much more; also a game like Go will end up with hundreds of playable pieces.

While one of them could / could probably question the idea of ​​adding so many controls, inquiring minds still want to know ..: Each part has its own copy of these code codes, as I believe it has or was inherited in our world of wonders, like ordinary events, and live only once during the memory work?

+3


source to share


2 answers


Each lambda is converted to a "normal" method at compile time, so the actual code for the lambas will not be duplicated. However, new EventHandler delegates that reference the code will be generated each time this method is run.



+5


source


As Michael Liu said, there is no overhead of using lambda. But you need to be aware of closures that store references to non-local variables (I mean, in the outer scope of a lambda). You can even get a memory leak when using closures.



How about event handlers? You can easily eliminate additional event handlers by using event routing in the parent \ container (if you're using a XAML-based UI framework).

+2


source







All Articles