1

Take the SPWeb object, for instance. I've seen that it can be obtained in any of the following ways:

(1)

SPWeb web = new SPSite(SPContext.Current.Site.ID).OpenWeb();

(2)

SPWeb web = SPContext.Current.Web;

(3)

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
    using (SPWeb web = site.OpenWeb())
    {
        //use the web object here
    }
}

Are (1), (2) and (3) identical in they way they work ultimately? If not, which is the better way, and what are the relative differences/advantages/disadvantages? Is there a better approach I've missed?

SNag
  • 17,681
  • 10
  • 54
  • 69

2 Answers2

0

As a general rule you should always wrap all object that implement IDisposable with using to avoid wasting of resources. So (1) is definetly bad practice, and (3) is good.

As for (2) SPContext objects are managed by SharePoint service and should never be disposed. It's recommended to avoid using them directly, instead following with pattern (3). You do not have full control over that object, and if you need to use RunWithElevatedPrivileges you also need to create your own SPSite/SPWeb. See for details.

So, to sum it up, always stick with pattern (3).

Community
  • 1
  • 1
Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96
0

You must always dispose SPSite and SPWeb objects when you create it. SPWeb is a COM object and garbage collector not clean memory when you finish to using it. For more information read this best practices article: Best Practices: Using Disposable Windows SharePoint Services Objects.