Use the using statement to automatically call Dispose in C#

example

The using statement makes it easier to free resources when you’re finished with an object.

Some objects take up important resources (such as brush handles or file handles) and only free them when they are destroyed. Because of the weird way C# implements non-deterministic finalization, you generally don’t know when those objects are actually destroyed (they may not be until the program ends), so you don’t know when the resources are freed.

Many classes that use scarce resources provide a Dispose method to free their resources. If an object has a Dispose method, you should always call it when you are done with the object. Unfortunately it’s easy to forget to do that. It can also be tricky to call Dispose in odd cases, for example when control jumps out of the code due to an exception.

To solve these problems, most of these classes also implement the IDispose interface and that lets you use them in a using statement. The using statement automatically calls the object’s Dispose method when the using block ends, even if it ends because of an exception.

This example uses the following code to draw a diamond with a custom Pen.

// Draw a diamond.
private void Form1_Paint(object sender, PaintEventArgs e)
{
    // Clear.
    e.Graphics.Clear(this.BackColor);
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

    // Make points to draw a diamond.
    Point[] points =
    {
        new Point((int)(this.ClientSize.Width / 2),
                  0),
        new Point(this.ClientSize.Width,
                  (int)(this.ClientSize.Height / 2)),
        new Point((int)(this.ClientSize.Width / 2),
                   this.ClientSize.Height),
        new Point(0,
                  (int)(this.ClientSize.Height / 2)),
    };

    // Make the pen.
    using (Pen dashed_pen = new Pen(Color.Red, 10))
    {
        dashed_pen.DashStyle = DashStyle.Dot;
        e.Graphics.DrawPolygon(dashed_pen, points);
    }
}

This code clears the Graphics object and sets its SmoothingMode property to produce a smooth result. It then creates an array of points that define a diamond shape.

The code then creates a thick red Pen, sets its DashStyle property to produce a dotted line, and uses it to draw the diamond.

The Pen class uses scarce graphics resources that you should free as soon as possible, so the code uses a using statement to ensure that Dispose is called.

The simplest syntax for the using statement is as shown in this code: declare and initialize the object in the using statement. When the using block ends, the object is disposed.

The Graphics and Brush classes also have Dispose methods so you should use using for them as well.

However, you should not call Dispose on an object that you will need to use later or that you did not create yourself. In this example, the Graphics object was created by the system code that raised the Paint event handler, so you shouldn’t dispose it.

It can also be hard to know whether you’ll need an object later. For example, the Bitmap class also has a Dispose method, but if you display a Bitmap in a PictureBox or some other control, the program may need to use the Bitmap to redraw the control later. Your code doesn’t need the object, but the program does. If you call the Bitmap‘s Dispose method, the program crashes the next time it needs to redraw the control.

The moral is: always use using (unless you shouldn’t).


Download Example   Follow me on Twitter   RSS feed




This entry was posted in OOP, syntax and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *