4

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?

SPArcheon
  • 6,868
  • 1
  • 30
  • 47
variable
  • 4,473
  • 13
  • 75
  • 139

2 Answers2

9

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.

Nadeem Yousuf-AIS
  • 18,707
  • 4
  • 28
  • 59
  • http://blogs.technet.com/b/stefan_gossner/archive/2008/12/05/disposing-spweb-and-spsite-objects.aspx 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 05: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-AIS Apr 23 '14 at 05: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 '14 at 06:10
2

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.