HtmlControl Removal

Following the recommendation of code analysis in VS to call Dispose on an object (which I had not previously), I ended up using this method:

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

It confused me a little if I placed this object after adding it to the Controls collection, is that such a good idea?

How does it still work? Is this because the Controls.Add method provides the object after use, rather than holding it?

+7
source share
3 answers

I would say that this code should not work, but if you say that it works, then the only thing I can think of is:

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

Hope this helps.

+2
source

If a method is called for favicon that uses any of the unmanaged resources, it will throw an exception.

From msdn:

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

using msdn instruction

+1
source

I assume that code analysis gave you the CA2000: delete objects before losing scope before you change the code. The problem is that you should not dispose of your object, because you want to use it even after returning from the method (it was added to the collection).

You can either suppress the message using the SuppressMessage attribute , or you can rewrite the code to really paranoid:

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

The normal flow of this code adds favicon to the collection, which is then responsible for removing it. However, an abnormal thread in which favicon.Attributes.Add throws an exception will position favicon before the exception is thrown.

In most cases, since the garbage collector ultimately gets the job done, you don't need a paranoid version of the code.

0
source

All Articles