Search code examples
c#using-statement

Is there a way to make a “using” statement terminate before a nested one?


When a field is used for creating another field, and then disposed – I see two options. First:

Image image = Image.FromFile(path);
Bitmap bitmap = (Bitmap)image.GetThumbnailImage(32, 32, null, new IntPtr());
image.Dispose();//not needed anymore.

//use bitmap

bitmap.Dispose();

Second:

using (Image image = Image.FromFile(path))
{
    using (Bitmap bitmap = (Bitmap)image.GetThumbnailImage(32, 32, null, new IntPtr()))
    {
        //use bitmap
    }
}

The logical one would be the first (because the Image isn’t needed when the Bitmap is used), but using statements are generally preferable over Dispose.

Is there a third way – to terminate the first using inside the second one?


Solution

  • Yes, there is: Put the code to produce the thumbnail image into a method:

    Bitmap GetThumbnail(string path)
    {
        using (Image image = Image.FromFile(path))
        {
            return (Bitmap)image.GetThumbnailImage(32, 32, null, new IntPtr());
        }
    }
    
    // ...
    
    using (Bitmap bitmap = GetThumbnail(path))
    {
        //use bitmap
    }
    

    Please note:
    I agree with Oded's comments. I would use this code not because it disposes image first, but because it is more readable.