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):