Disposing of objects in SharePoint

When writing code against the SharePoint API, there are several objects that you will more than likely work with that implement the IDisposable interface. These objects are stored in memory and will remain there until disposed of properly. Since many of these objects are quite large, and can be created quite frequently, this can cause a problem with performance in your SharePoint environment.

As a developer, it is your responsibility to be aware of which objects should be disposed of in your code. A great place to find details on this topic can be found on MSDN. Here are a couple of examples.


The wrong way:

SPSite site = new SPSite(“siteurl”);

The correct way:

using(SPSite site = new SPSite(“siteurl”))

     // Your code goes here


The wrong way:

SPWeb web = site.AllWebs[“webname”];

The correct way:

using(SPWeb web = site.AllWebs[“webname”])

     // Your code goes here

Other things to look out for:

  • The RootWeb object needs to be disposed.
  • The SPContext.Current.Site and SPContext.Current.Web should NOT be disposed.

I recommend reading the best practices provided on Microsft to learn the many different scenerios where you need to dispose of objects in your code.


The SPDisposeCheck tool can be run against your assembly help check for places in the code where objects are not being properly disposed. The tool can be added to Visual Studio, making it no hassle to run.

  1. In Visual Studio, select Tools —> External Tools
  2. Click Add and fill out the required fields (Use the following as an example)

Title:  SPDisposeCheck
Command: C:Program FilesMicrosoftSharePoint Dispose CheckSPDisposeCheck.exe 
Arguements: $(TargetName)$(TargetExt)
Initial Directory: $(TargetDir)
Use Output Window: Checked

To run the tool you can click on SPDisposeCheck under the tools menu and it will run against the selected project.

SharePoint Document Approval Process

How to increment a number with leading zeros