We have the following code:

    foreach (SPWeb website in collectionOfWebSites)
           // Some code, no dispose of website


SPDisposeChecker is reporting it as a memory leak. Should we dispose the website at the end of the foreach?


Yes, dispose the SPWeb here each time!

| improve this answer | |

Someone might need to back up me, but if you're getting an object from that collection, it does actually create an SPWeb instance each time (the collection is just a collection of object references rather than the objects themselves?), so you will indeed need to dispose of the object after each iteration.

| improve this answer | |
  • That is what I though, but after I posted the question I found this link blogs.msdn.com/b/rogerla/archive/2008/02/12/… which says that you need to dispose each instance of SPWeb. – Shiraz Bhaiji Sep 8 '10 at 11:19
  • 1
    I'm pretty sure as James says - it will create an SPWeb instance for each iteration. So yes you will need to dispose of it manually after you have finished with it. Although the SPWeb won't be accessible outside the foreach it will still waste resources if not disposed. – Anonymous Sep 8 '10 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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