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.
Martin liversage
source share