Search code examples
c#imagefor-loopbitmapdispose

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();
}

Solution

  • 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
            }        
        }     
    }