3

I am referring a SharePoint book and I found the following code snippet in an example in that book.

using (SPSite mySiteCollection = new SPSite(mySiteUrl))
{
    using (SPWeb mySPSite = mySiteCollection.RootWeb)
    {
       //your code here.
    }
}

I read through the usage of RootWeb property over OpenWeb() method all over the internet and found that we should never use RootWeb property inside of a 'using' statement. But in this book, they always use RootWeb for create SPWeb object. And everything works perfectly.

Can anybody tell me how should I use RootWeb property over OpenWeb method? And what are the pros and cons using each of them. Actually I found similar question in here. But it doesn't provide the answer for my question.

Jake
  • 582
  • 1
  • 6
  • 20

1 Answers1

4

The Property RootWeb always give you the root web of the site.
In addition - you get an existing instance and you should not dispose it or use it in Using statement. (It's basically the same.)

OpenWeb function creates a new instance you must dispose,
And it does not always give you the root web -
This function will open the website at the URL you provided to create your SPSite object. (mySiteUrl at your case.)

Edit:
From the Reflector:

[ClientCallable]
public SPWeb RootWeb
{
    get
    {
        if (this.m_rootWeb == null)
        {
            this.m_rootWeb = this.OpenWeb(this.ServerRelativeUrl);
            this.m_rootWebCreated = true;
        }
        return this.m_rootWeb;
    }
}

You can see that the instance is created only once,
And from then on - you get the existing instance.

Reflecting OpenWeb:

public SPWeb OpenWeb(string strUrl, bool requireExactUrl)
{
    SPGlobal.ValidateWebName(strUrl, true);
    if (!this.IsValidWebUrl(strUrl))
    {
        throw new ArgumentException(SPResource.GetString("InvalidUrl", new object[]
        {
            strUrl
        }));
    }
    string url = this.MakeFullUrl(strUrl);
    return new SPWeb(this, url, requireExactUrl);
}
banana
  • 694
  • 6
  • 21