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

Suppose we have code:

CASE 1:

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
    {
        SPWeb web = site.RootWeb;
    } 

Do we need to dispose the SPWeb in this case?

CASE 2:

 using (SPSite site = new SPSite(SPContext.Current.Web.Url))
        {
            SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb();
        } 

Do we need to dispose the SPWeb in this case? Or does it get automatically disposed after the using block disposes the SPSite object?

share|improve this question

2 Answers 2

up vote 7 down vote accepted

In first case SPWeb web = site.RootWeb; SPWeb does not need to be disposed as SPWeb is retrieved from RootWeb. However, in second case SPWeb needs to be explicitly disposed. Mere disposal of SPSite is not enough. So the code should look like:

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
    using (SPWeb web = site.OpenWeb())
    {

    }
} 

Note: there is no need to create an SPSite object again when opening SPweb as it is already present.

share|improve this answer
    
blogs.technet.com/b/stefan_gossner/archive/2008/12/05/… This articles says: "dispose for the SPSite object in position 1 will automatically dispose all SPWeb objects bound to the SPSite object.", can you check please. –  variable Apr 23 at 5:17
    
It also mentions "You should dispose a SPWeb or SPSite object after the last access to a child object of this object." This is done by having the using statement. using is equivalent to try catch finally –  Nadeem Yousuf Apr 23 at 5:25
1  
Just curious, do you know how RootWeb is disposed by SPSite? When decompiling the SharePoint DLL I can't see where it is disposed at all. I think m_openedWebs are all disposed of properly, but RootWeb is not part of these. I know it is disposed, I just can't see where it is done –  eirikb Apr 23 at 6:10

No, we need to dispose the SPWeb object separately. Because we are not assigning current SPWeb context to the web variable.

Here, 1. We are first getting the SPSite object from current context web url 2. Then we are retrieving the SPWeb object from SPSite 3. After that we are assigning that variable to the SPWeb.

So, we need to dispose the SPWeb object separately in Case 2 to clear the garbage memory. In Case 1: SPWeb object (web) is automiatically disposed by site.

share|improve this answer
    
Are you sure that: SPWeb web = site.RootWeb; needs to be disposed? –  variable Apr 23 at 5:18
    
No need. For Case 1, the web object automatically disposed by site. –  Shantha Kumar Thambidurai Apr 23 at 5:33

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.