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

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?

share|improve this question
up vote 4 down vote accepted

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.
share|improve this answer
So would throwing a using around the promo1List declaration make everything dispose correctly? – Abe Miessler Mar 23 '12 at 20:16
please, refer to my update – Kai Mar 23 '12 at 20:33
Interesting. So it's not possible to dispose of the site object without declaring it on its own? – Abe Miessler Mar 23 '12 at 20:36
I don't know another way... – Kai Mar 23 '12 at 20:49
Well you could call promo1List.ParentWeb.Site.Dispose(), but adding the using as Kai suggest is a way better solution – Per Jakobsen Mar 23 '12 at 22:03

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.