I’m having a weird situation that I’m trying to understand. This piece of code is giving CA2000 (call Dispose on object before all references… ) :
var ms = new MemoryStream(Encoding.Default.GetBytes(DefaultControlTemplateXaml));
using(ms)
{
var x = XamlReader.Load(ms);
_defaultControlTemplate = x as ControlTemplate;
}
However, this other piece is not:
var ms = new MemoryStream(Encoding.Default.GetBytes(DefaultControlTemplateXaml));
try
{
var x = XamlReader.Load(ms);
_defaultControlTemplate = x as ControlTemplate;
}
finally { ms.Dispose(); }
As per Microsoft’s documentation:
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
So I’m really at a lost here… aren’t those two statements supposed to be identical?
Update
Since people insist (without reading my comment) on explaining the using ettiquete. I’ll put it this way:
using (var ms = new MemoryStream(Encoding.Default.GetBytes(DefaultControlTemplateXaml)))
{
var x = XamlReader.Load(ms);
_defaultControlTemplate = x as ControlTemplate;
}
This still gives CA2000 on fxcop, so the original question remains.
Update 2
Adding some screenshots so that you can see this is Visual Studio 2010 and the whole function.
First version (gives warning):

Second version (ok):

(Removed some stuff that didn’t apply to the question and also some incorrect stuff about
ThreadAbortException.)You are probably experiencing a false positive reported by CA2000. You can search Microsoft Connect for CA2000. There exists quite a few issues (not all of them being false positive bugs).
I personally have turned CA2000 off in some projects because of these false positives. I’m using Visual Studio 2010 with Code Analysis and I just verified that, yes, after having to suppress CA2000 too many times we decided to turn it off in the project I’m working on right now.