I was just wondering if you need to unregister events before creating a new instance of an object... for clarity:
Say I have a Hyperlink and have already created an instance for it.
Hyperlink m_myHyperlink = new Hyperlink();
In the code where the control sets the hyperlink up there are events registered to it, based off certain conditions.
...
private void SetValue(...)
{
...
m_myHyperlink = new Hyperlink(new Run(displayText));
Uri path = null;
if (Uri.TryCreate(link, UriKind.Absolute, out path)
{
m_myHyperlink.NavigateUri = path;
m_myHyperlink.RequestNavigate += new RequestNavigateEventHandler(foo);
}
else
{
m_myHyperlink.Click += new RoutedEventHandler(bar);
}
}
...
So, the next time the value is set, a new instance is created for m_myHyperlink and events are registered based on the conditions.
Do, I need to worry about unregistering the events before the new instance is created? So, the code would look something like this.
...
private void SetValue(...)
{
...
// I know one of these would not be registered, but it is legal to attempt to
// unregister it anyways...
m_myHyperlink.RequestNavigate -= new RequestNavigateEventHandler(foo);
m_myHyperlink.Click -= new RoutedEventHandler(bar);
m_myHyperlink = new Hyperlink(new Run(displayText));
Uri path = null;
if (Uri.TryCreate(link, UriKind.Absolute, out path)
{
m_myHyperlink.NavigateUri = path;
m_myHyperlink.RequestNavigate += new RequestNavigateEventHandler(foo);
}
else
{
m_myHyperlink.Click += new RoutedEventHandler(bar);
}
}
...
I'm guessing that the GC can dispose of the old instance just fine without unregistering the events, but wanted to make sure and see if there is any benefit to help the GC of the old instance by unregistering the events before creating the new instance.