Say I have the following code:

 SPList promo1List = site.WebApplication.Sites[0].RootWeb.Lists.TryGetList("promotions");

Will this lead to the SPSite object Sites[0] not being disposed? I ran SPDisposeCheck against my code and it came up with a bunch of warnings about the above.

According to their documentation: SPSiteCollection[] indexer returns a SPSite object which needs to be disposed.

Is this accurate or is this just a false positive?

1 Answer 1


Yes, this code leads to memory leak.
I prefer to use this (or this one for 2007 sharepoint) page every time, when I doubt if object should be disposed. According section SPSiteCollection [ ] Index Operator you must dispose SPSite object.

So, in order to correct dispose SPSite in your example, you need to use this code:

using (var mySite = site.WebApplication.Sites[0])
    SPList promo1List = mySite.RootWeb.Lists.TryGetList("promotions");
    //no need to dispose RootWeb, because the dispose cleanup for RootWeb is handled 
    //automatically by both SharePoint Foundation and SharePoint Server.
  • So would throwing a using around the promo1List declaration make everything dispose correctly? Mar 23, 2012 at 20:16
  • please, refer to my update Mar 23, 2012 at 20:33
  • Interesting. So it's not possible to dispose of the site object without declaring it on its own? Mar 23, 2012 at 20:36
  • I don't know another way... Mar 23, 2012 at 20:49
  • Well you could call promo1List.ParentWeb.Site.Dispose(), but adding the using as Kai suggest is a way better solution Mar 23, 2012 at 22:03

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.