Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to dispose objects? C#

I wrote a for-loop that inside of it I declared a new Image, so should I Dispose it every time inside the internal for-loop, or once it is all finished, and what's the difference?

Here's an example to make things clear, Should I use this:

for (int i = 0; i < 10; i++)
{
    Image imgInput = new Image();

    for (int j = 0; j < 100; j++)
    {
        // Here is a code to use my image

        Image.Dispose();
    }
}

OR:

for (int i = 0; i < 10; i++)
{
    Image imgInput = new Image();

    for (int j = 0; j < 100; j++)
    {
        // Here is a code to use my image
    }

    Image.Dispose();
}
like image 510
Ahmad Avatar asked Mar 24 '26 17:03

Ahmad


1 Answers

We usually wrap IDisposable into using in order to guarantee that the instance (i.e. unmanaged resources) will be disposed rain or shine. If you want to declare Image outside of the inner loop:

for (int i = 0; i < 10; i++)
{
    using (Image imgInput = new Image()) 
    {
        for (int j = 0; j < 100; j++)
        {
            ...
            // In all these cases the resource will be correctly released: 

            if (someCondition1) 
                break;

            ...

            if (someCondition2) 
                return;

            ...

            if (someCondition3) 
                throw new SomeException(...);

            ...  
            // Here is a code to use my image
        }
    }
}

That's why, we should not call Dispose explicitly. Please note, that both code excerpts you've provided will result in resource leakage in case of someCondition2 or someCondition3.

Same scheme if you want to declare Image within the nested loop:

for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 100; j++) 
    {
        using (Image imgInput = new Image()) 
        {
            // Here is a code to use my image
        }        
    }     
}
like image 60
Dmitry Bychenko Avatar answered Mar 26 '26 05:03

Dmitry Bychenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!