Introduction
It’s very important to dispose our objects in SharePoint to avoid Memory Leaks, this article will explain dispose Patterns or methods in SharePoint code.
Method 1 - Manually calling Dispose()
The most general and simple approach to dispose your objects is to simply call the .Dispose() method of your objects:
- SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/");
- // Do stuff
- site.Dispose();
A more common approach is to encapsulate the code in a using-block where the object will be automatically disposed when we are reaching the end of our block.
- using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"));
- {
- // Do stuff
- }
Whenever you are expecting to catch an exception and need to handle them – a better approach for disposing is to create a try-finally block and dispose the object in the finally-block.
Sample 1: Without exception handling.
- SPSite site = null ;
- try
- {
- site = new SPSite ("http://laxman-sharepoi:1000/admin/");
- // do stuff
- }
- finally
- {
- if (site!=null ) site.Dispose();
- }
- SPSite site = null ;
- try
- {
- site = new SPSite ("http://laxman-sharepoi:1000/admin/");
- // do stuff
- }
- catch (Exception ex)
- {
- // Handle the exception
- // Possibly genrate logs
- }
- finally
- {
- if (site!=null ) site.Dispose();
- }
In some scenarios it might be a necessity to use mix oapproach for disposing.
- using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"))
- {
- foreach (SPSite site in site.WebApplication.Sites)
- {
- try
- {
- // Do stuff
- }
- catch (Exception ex)
- {
- // Log and handle exceptions
- }
- finally
- {
- if (site!=null ) site.Dispose();
- }
- }
- }

Join the conversation! Your thoughts help the community grow.