Leverage “using” in C#

Here is some code that creates a thumbnail image and converts the Image object to a byte array.

 

// Convert Image to byte array

Image photoImg;

Image thumbPhoto;

MemoryStream ms;

 

try

{

    // Create an Image object from a file.

    // PhotoTextBox.Text is the full path of your image

     photoImg = Image.FromFile(PhotoTextBox.Text);

 

    // Create a Thumbnail from image with size 50x40.

    // Change 50 and 40 with whatever size you want

    thumbPhoto = photoImg.GetThumbnailImage(50, 40, null, new System.IntPtr());

    ms = new MemoryStream();

 

    thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

    imgBytes = ms.ToArray();       

}

catch (Exception exp)

{

    MessageBox.Show("Select a valid photo!");

    PhotoTextBox.Select();

    return;

} 

 

What is wrong with the above code? Actually nothing. The code may throw an exception when there is a problem in creating a thumbnail or not finding the correct image file.

 

So what happens, if an exception occurs? The Image and MemoryStream objects will not be disposed immediately and it is possible not until you restart your machine.

 

Now we can solve this problem by using a finally statement and disposing objects there. We can simply add the following code at the end of the above code. It will ensure that all objects are disposed.

 

finally

{

    photoImg.Dispose();

    thumbPhoto.Dispose();

    ms.Close();

    ms.Dispose();

}

 

C# provides a very powerful syntax using, that does the same but with less mess in the code. The following code does the same as code listed above including the finally statement. All objects created with the using statement are automatically destroyed or marked to be destroyed by GC once the thread execution is out of the using statement.

 

try

{

    // Create an Image object from a file.

    // PhotoTextBox.Text is the full path of your image

    using (Image photoImg = Image.FromFile(PhotoTextBox.Text))

    {

        // Create a Thumbnail from image with size 50x40.

        // Change 50 and 40 with whatever size you want

        using (Image thumbPhoto = photoImg.GetThumbnailImage(50, 40, null, new System.IntPtr()))

        {

            // The below code converts an Image object to a byte array

            using (MemoryStream ms = new MemoryStream())

            {

                thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                imgBytes = ms.ToArray();

            }

        }

    }

}

catch (Exception exp)

{

    MessageBox.Show("Select a valid photo!");

    PhotoTextBox.Select();

    return;

} 

 

Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.