what happens if i link a method of some object to a delegate, and then dispose of the object?
Like this:
class Hunter
{
public event Action Shoot;
public execute()
{
Form formBabySeal = new Form();
Shoot += formBabySeal.Close;
formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
if (Shoot != null)
{
Shoot(); //event is null?
}
}
}
formBabySealis notnulljust because you dispose it. So,formBabySeal.Close()will be called.Your code is equivalent to this when looking at what methods are called:
This will close the form (first call to
Close) and the second call won’t do anything, because the form is already closed.However, as Steve points out in the comment section, your code will introduce a memory leak, because
Shootstill holds a reference to theClosemethod offormBabySealand because of thisformBabySealwill be kept alive as long as the instance of the classHunteris alive.