Ahmad Ahmad - 10 days ago 5
C# Question

Declaring a disposable object: inside or outside a loop?

Should I use

using
block inside a loop or outside of it? Is there any sensible performance difference? Is there any difference in the case of
Graphics
object? While the second approach may seem better, the
while
could be a long block and make the code less readable.

while (i < 100)
{
using(Graphics g = Graphics.FromImage(bitmap)
{
g.DrawImage(...);
}
}


vs.

using(Graphics g = Graphics.FromImage(bitmap)
{
while (i < 100) // a long while block
{
// I may use other functions such as g.DrawLine .. or g.DrawText ...
// Moreover while could be a long block
g.DrawImage(...);

}
}

Answer

As a rule of thumb, place the using inside the loop if you plan to use the object only once OR the object is not designed to be reused (SQLCommand class come to mind as an example). Otherwise place it outside the loop.

In your specific case, if your intent is to draw the same image 100 times, then outside the loop is the way to go. On the other hand, if your intent is to draw 100 distinct images inside a loop, then the only way it could work is to place the using inside the loop, because the Graphics object cannot be reused with another image.