I'm trying to understanding the object clean up process.

using (SPSite siteCollection = new SPSite(siteUrl))
  SPWeb site = siteCollection.RootWeb;
  foreach (SPList list in site.Lists)
     if (!list.Hidden)

Do I need to wrap a second using against the SPWeb object in the code above?

I've read somewhere that this is not needed because wrapping a using around the SPSite will clean up any child web.

  • I would recommend to use the SP Dispose Checker Tool that can help to find dispose issues. It's not magic bullet, but it can help to avoid some common mistakes.
    – Steve B
    Jun 27, 2012 at 15:04

1 Answer 1


Both SPSite and SPWeb objects implement the IDisposable interface. When the SPSite object finally gets disposed it will loop through the list and ensure that all SPWeb objects associated with this SPSite object also get disposed.

This might lead to the assumption that just disposing all SPSite objects rather than disposing each individual SPWeb object would be sufficient to minimize the memory usage. In theory this is correct. But it will postpone the dispose of the SPWeb object to the time when the SPSite object gets disposed. So the dispose does not happen right after the SPWeb object is no longer used but much later.

Therefore, SPSite and SPWeb objects should be disposed in the same method they get allocated. That's the best method to ensure that no disposed can be missed and to ensure that a dispose does not occur for an object that will be used later.

Reference: http://blogs.technet.com/b/stefan_gossner/archive/2008/12/05/disposing-spweb-and-spsite-objects.aspx

Regarding your code: You can use using statement or finally block to Dispose the SPWeb object.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.