1

if i do somthing like this, will i get memory leak?

gb002.Controls.OfType<Button>().ToList().ForEach(b => {
b.MouseEnter += (sender, evnt) => Button_MultiHandler(sender, evnt, Color.Orange);
b.MouseLeave += (sender, evnt) => Button_MultiHandler(sender, evnt, backColor);});

private void Button_MultiHandler(object sender, EventArgs e, Color c)
{
    Button button = sender as Button;
    if(button != null)
    {
            button.BackColor = c;
    }
} 
  • 1
    There are memory leaks and then there are unnecessary allocations. Are you sure your professor wasn't talking about the latter? Creating a list just so you can call `ForEach` on it is an unnecessary allocation when you can do a `foreach` loop. – madreflection May 19 '21 at 21:11
  • foreach (Button b in gb002.Controls) { b.MouseEnter += (sender, evnt) => Button_MultiHandler(sender, evnt, Color.Orange); b.MouseLeave += (sender, evnt) => Button_MultiHandler(sender, evnt, backColor);} – Tomasz Cicherski May 19 '21 at 21:16
  • will this work better? – Tomasz Cicherski May 19 '21 at 21:16
  • 2
    "leak" is a poorly-defined term. Traditionally, it means memory that is no longer referenced but which was not returned to the memory manager and thus is abandoned and cannot be used again. In that sense, leaks are _impossible_ in managed, garbage-collected environments like .NET. There are scenarios that IMHO are more properly described as "pack-ratting", i.e. hanging on to objects that are no longer needed; the memory is still accessible and _could_ be reused, but the code will never do so. The ... – Peter Duniho May 19 '21 at 21:18
  • 1
    ... above does not seem to fit into either of those categories. There are unnecessary allocations and inefficiencies, but everything you posted seems to be doing real work. It's sloppy, but not _wrong_ per se. See duplicate for extensive details about memory leaks and leak-like behaviors as they related to event handlers. – Peter Duniho May 19 '21 at 21:18
  • 1
    _"will this work better?"_ -- using `foreach` instead of `List.ForEach()` is better, but you should still use `OfType – Peter Duniho May 19 '21 at 21:20

0 Answers0