Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing a HtmlControl

On the advice of Code Analysis in VS to call Dispose on an object (which I wasn't previuosly) I ended up with a method containing this:

using (var favicon = new HtmlLink
                         {
                             Href = "~/templates/default/images/cc_favicon.ico"
                         })
{
    favicon.Attributes.Add("rel", "shortcut icon");
    Header.Controls.Add(favicon);
}

This confused me slightly, if I dispose this object after adding it to the Controls collection is that such a good idea?

How does this still work? Is it because the Controls.Add method disposes the object after use as opposed to holding on to it?

like image 583
Mantorok Avatar asked Sep 21 '11 08:09

Mantorok


2 Answers

I would say that this code shouldn't work but if you say it's working then the only things I can think of are:

  • Header.Controls.Add add a copy of the object so there is no problem disposing the original.
  • The Dispose method does not clean anything that is used later.

Hope this helps.

like image 131
Ignacio Soler Garcia Avatar answered Nov 01 '22 09:11

Ignacio Soler Garcia


If a method on favicon is called that uses any of the unmanaged resources it will give exception.

From msdn:

You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.

using statement msdn

like image 25
Peter Avatar answered Nov 01 '22 10:11

Peter