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

Suppose we have code:


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

Do we need to dispose the SPWeb in this case?


 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
up vote 8 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… 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 '14 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 '14 at 5:25
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 '14 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 '14 at 5:18
No need. For Case 1, the web object automatically disposed by site. – Shantha Kumar Thambidurai Apr 23 '14 at 5:33

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.