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:
  1. SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/");
  2. // Do stuff
  3. site.Dispose();
Method 2 - Encapsulating the statement in a using() block

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.
  1. using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"));
  2. {
  3. // Do stuff
  4. }
Method 3 - Utilize a try/finally block

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.
  1. SPSite site = null ;
  2. try
  3. {
  4. site = new SPSite ("http://laxman-sharepoi:1000/admin/");
  5. // do stuff
  6. }
  7. finally
  8. {
  9. if (site!=null ) site.Dispose();
  10. }
Sample 2: With exception handling.
  1. SPSite site = null ;
  2. try
  3. {
  4. site = new SPSite ("http://laxman-sharepoi:1000/admin/");
  5. // do stuff
  6. }
  7. catch (Exception ex)
  8. {
  9. // Handle the exception
  10. // Possibly genrate logs
  11. }
  12. finally
  13. {
  14. if (site!=null ) site.Dispose();
  15. }
Method 4 - A mix mode approach

In some scenarios it might be a necessity to use mix oapproach for disposing.
  1. using (SPSite site = new SPSite ("http://laxman-sharepoi:1000/admin/"))
  2. {
  3. foreach (SPSite site in site.WebApplication.Sites)
  4. {
  5. try
  6. {
  7. // Do stuff
  8. }
  9. catch (Exception ex)
  10. {
  11. // Log and handle exceptions
  12. }
  13. finally
  14. {
  15. if (site!=null ) site.Dispose();
  16. }
  17. }
  18. }