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.

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);
}
  • Interesting. Are you sure that new SPSite(mySiteUrl).RootWeb will not create a new instance (SPWeb) of the root web of the site collection? – Vardhaman Deshpande Oct 13 '13 at 11:16
  • @VardhamanDeshpande - I edited my answer. – banana Oct 13 '13 at 11:49
  • OK so RootWeb creates a new instance only the first time it is called. And open web will create a new instance every time its called. I have added the reflected code for OpenWeb too. Ok so now the question arises: Should't we dispose the SPWeb which is created by RootWeb the first time? – Vardhaman Deshpande Oct 13 '13 at 12:05
  • 1
    @VardhamanDeshpande - See here: Should I dispose of this SPWeb? and MSDN. (Search SPSite.RootWeb) – banana Oct 13 '13 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.