4

What is best practice with the Using statement when working with SharePoint Objects. When and how should you use the Using statement, so objects used are disposed, etc?

4 Answers 4

13

The key is if your code creates an instance of an SPSite or SPWeb you must dispose of it. However, if you use an instance from SPContext.Current you should not dispose of it. i.e. Dispose of what you create, whether that is directly or indirectly.

Example of creating your own instance, so using is required:

using(SPSite site = new SPSite("http://server"))
{
}

Example of using an existing object from the SPContext, so using is not required:

SPWeb web = SPContext.Current.Web;
SPSite site = SPContext.Current.Site;

Example of creating your own instance of an SPWeb by calling OpenWeb():

using(SPWeb web = SPContext.Current.Site.OpenWeb("http://server/mywebsite"))
{
}

Also, be careful to dispose of objects even if an exception is thrown, by putting the dispose call in the finally block.

try
{
   site = new SPSite("http://server");
   web = site.OpenWeb();
}
catch(Exception e)
{
   //handle it
}
finally
{
   if (web != null)
      web.Dispose();

   if (site != null)
      site.Dispose();
}

These are just a few examples, but there are many others. Here is a good reference.

In addition, you can make use of the SPDisposeCheck tool.

1
3

There is a best practices guide from microsoft about when to dispose which objects (SPSite, SPWeb): http://msdn.microsoft.com/en-us/library/ee557362(v=office.14).aspx

Also there is a dispose checker tool provided by microsoft: http://archive.msdn.microsoft.com/SPDisposeCheck

1

The golden rule seems to be: If you own the object (i.e. created it by using the new operator), then you dispose of it. If the object comes from another object created by SharePoint object model itself, then you don't. Use SPDisposeCheck to be sure as Laurie indicated.

0

While the above answer are all fine, I just want to add some stuff for clarity.

To see if the object you are using needs to be disposed, you can check the MSDN reference of the class (press F1 when the cursor is on the declaration in VS) and check if the class implements IDisposable. If so, only dispose of the object if you actually made the object (with either a new statement, or an OpenXXX() method or similar).

The try-catch-finally construction is never needed for these objects if you use the using statement, because in compilation the using statement will be converted to a try-catch-finally constuction as seen in Laurie's final example. The using statement is preferable because it is much more elegant and will make your code more readable.

The SPDisposeCheck seems like a nice tool, but with a bit of common sense you will probably not need it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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