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?
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:
Hope this helps.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With