I have the following function.
What it does is, given a Control (most likely a windows form) i want to have all of the controls contained that “obey” the Rules ( a function screening the controls i want ) subscribe to an event (lets say KeyDown).
The question is: how do i unsubscribe? Or more importantly, do i need to?
Since i will be using this one on the Load event of forms on the form itself will i really need to unsubscribe if the form closes?
(after some light reading and a little understanding of the GC i suspect i don’t need to unsubscribe but I’m not sure)
//an example of using the function
private void Form1_Load(object sender, EventArgs e)
{
MyEventHandler.CreateKeyDownEventHandlers(this);
}
//the function
public static void CreateEventHandlers(Control Ctrl)
{
foreach (Control c in Ctrl.Controls)
{
//bool Rules(Control) a function that determines to what controls'
//events to apply the handler
if ( Rules(c) )
{
c.KeyDown += (s, e) =>
{
// do something
};
}
//a control might be a groupbox so we want their contained
//controls also
if (c.Controls != null)
{
if (c.Controls.Count > 0)
{
CreateEventHandlers(c);
}
}
}
}
This is my first try with events, delegates, anonymous functions and lambdas so if i did something really stupid tell me.
First, I think you cannot unsubscribe an anonymous function unless it’s assigned to a handler variable and that variable is addded to and then removed from the event.
Whether you need to unsubscribe: Think about the object lifetimes. You create anonymous functions in a static method and attach the to controls of which I assume you control the lifetimes.
When you dispose one of these controls, they will no longer be referencing the anonymous functions and the GC can kill them (the anonymous functions), so you don’t need to unsubscribe.
If the situation was reversed and something that was created in the static method referenced the controls, as if a control delegate was added to an event in the static context, then the GC couldn’t take care of the controls until the reference to them was removed, which wouldn’t happen if it was done in the static method.