Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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

1 Answer 1

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

 
discard

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.