I’m wondering why does Visual Studio code analysis give a warning with this little bit of code:
byte[] data = File.ReadAllBytes("myImage.png");
using (MemoryStream mem = new MemoryStream(data))
using (Bitmap bmp = new Bitmap(mem))
{
// do something with the bitmap
}
The error is:
Object ‘mem’ can be disposed more than once in method … To avoid
generating a System.ObjectDisposedException you should not call
Dispose more than one time on an object.
And how to correct this? (Yes, I could load bitmap directly from file, but in my real project I have my own file format where multiple images are saved into one file and therefore I need a MemoryStream to load the data from a specific range in the file)
with regards to the second reliability warning, it seems like when this situation occurs, code analysis will complain with either CA2000 or CA2202 regardless of what you do. There’s multiple complaints about this, here’s one for your enjoyment.
Just to see if it’s particular to using syntax, I expanded out the using into a try catch block and you get the same behavior.
edit: There is, as you (Jaska) pointed out, a note from Microsoft about flagging intent about the memorystream in the Bitmap’s using block:
I’m glad to see that this works, but at the same time it’s a bit uglier than using an anonymous memorystream in the bitmap’s constructor. Ah well.