SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
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 '12 at 15:04
up vote 5 down vote accepted

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.


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

share|improve this answer
Thanks this makes sense. So it will eventually clean up in the end when SPSite is disposed but just postpone until this time. I see the danger there now cheers. – TheLazyChap Jun 28 '12 at 2:27
Here is another good reference for 2010: – Mike Oryszak Jun 28 '12 at 13:14

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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