Dispose SharePoint Objects Correctly

In the world of managed-code, the garbage-collector typically clears objects in memory automatically for you. Remember malloc() and free() in C++? In managed code, you just typically write “variable = new Object()” and the CLR will allocate the memory for you. In unmanaged world like C++, you had to allocated memory and then deallocate memory after use.

Most objects in ASP.NET Framework are allocated/deallocated in memory automatically. However, there are objects that inherit from the IDisposable. You have to explicitly dispose objects that implement the IDisposable interface or you will run the risk of memory leaks. Some examples of ASP.NET objects that implement IDisposable include Connection, Command, Adapater, and Reader objects (in the System.Data namespace). You can perform any of the following to dispose these objects properly:

SQLConnection connection = new SQLConnection(connectionString);

//use the connection object here



Or, you can using the using statement:

using(SQLConnection connection = new SQLConnection(connectionString))


                //use connection object here

} // don't have to call Dispose(); the using statement will dispose connection correctly

When working with SharePoint API (SharePoint .NET libraries and not the SharePoint Web services), it is important to know when and when not to dispose SharePoint objects. If you do not dispose objects in SharePoint, your server will run the risk of memory leaks which can lead to performance issues. If you dispose objects that you’re not supposed to call Dispose() on, you might inadvertently kill the SharePoint application! For example, the following code will definitely kill the SharePoint Web application:

SPContext.Current.Web.Dispose(); // expect calls to your help-desk with this line in your code!


If you are the custodian of the SharePoint farm, you might want to use the SP Dispose Checker Tool to ensure that the custom .NET assemblies being installed on your farm will not cause memory leaks.

For complete guidance on when and how to dispose SharePoint objects, you can read the SP Dispose Team blog.

1 Comment

Leave a Reply

Your email address will not be published.