Search code examples
c#memorygarbage-collectionidisposable

Do I need to dispose of a resource which is not actually used?


i have a stupid question, but i want to hear the community here.

So here is my code:

using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) 
{ 
      return true; 
} 

My question, is it any different than:

(FtpWebResponse)request.GetResponse();
return true;

Which one is better in general? which one in terms of GC and why?


Solution

  • The first is better, but not in terms of GC. WebResponse implements IDisposable because it has resources that need to be released such as network connections, memory streams, etc. IDisposable is in place because you, as the consumer, know when you are done with the object and you call Dispose to notify the class you're done with it, and it is free to clean up after itself.

    The using pattern really just calls Dispose under the hood. E.g. your first example is actually compiled to be this:

    FtpWebResponse response = (FtpWebResponse)request.GetResponse()
    try
    {
    }
    finally
    {
        ((IDisposable)response).Dispose();
    }
    return true;
    

    This is separate from the garbage collector. A class could also clean up resources in the finalizer, which gets called from GC, but you should not rely on that to happen for two reasons:

    1. It could be a very long time before GC finally comes around, which means those resources are sitting there being consumed for no good reason.
    2. It might not actually clean up resources in the finalizer anyway