I’ve come across a routine that does something like this:
static public Bitmap byte2bmp(byte[] BitmapData)
{
MemoryStream ms = new MemoryStream(BitmapData);
return (new Bitmap(ms));
}
I’m worried this might not be the best recommended approach. Does the ms gets disposed properly in this scenario?
Or would it be better to assign the result to a temporary Bitmap, dispose of the stream, and then return the temp object?
static public Bitmap byte2bmp(byte[] BitmapData)
{
MemoryStream ms = new MemoryStream(BitmapData);
Bitmap temp=new Bitmap(ms);
ms.Dispose();
return (temp);
}
I was hoping the “using” might be used in this scenario, but am not sure it would behave properly or not:
static public Bitmap byte2bmp(byte[] BitmapData)
{
using(MemoryStream ms = new MemoryStream(BitmapData))
{
return (new Bitmap(ms));
}
}
What is the most effective/proper solution? Thanks!
You’re correct in worrying that the first approach will fail to dipose
ms. As a matter of good practice, you should always call theDisposemethod on objects that implementIDisposable.I recommend adopting the last approach. You can be confident that a
usingstatement will dispose of the object as expected even if you return in the middle of it.Here’s how the code would break down during run time: First, the return expression will be evaluated, then the try-finally block (for which the
usingstatement is simply syntactic sugar) will be executed, and finally the method will return.The only case in which you might encounter issues with returning in the middle of a
usingstatement is if you return the variable from theusingstatement itself. Of course, this would cause issues anyway if you retained any reference to the variable beyond the scope of theusingblock.Also see: Best practice regarding returning from using blocks