Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CA2000 : Microsoft.Reliability : Call System.IDisposable.Dispose on object 'dt' before all references to it are out of scope

Tags:

c#

When I run code analysis tool I get the following:

Warning 1 CA2000 : Microsoft.Reliability : In method 'Class1.test.testMethod()', object 'dt' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'dt' before all references to it are out of scope. How to resolve the warnings??

public void testMethod()
{
   DataTable dt = new DataTable();
   DataTable dt1= new DataTable();
      try
      {
         if (dt.Rows.Count == 0)
         {
            dt1.Merge(dt);
         }
      }
      catch
      {
         throw;
      }
      finally
      {
         if (dt != null) dt.Dispose();
         if (dt1 != null) dt1.Dispose();
      }
}
like image 497
salique ahmad Avatar asked May 20 '13 11:05

salique ahmad


2 Answers

Not really sure why you are getting that error, but you can try using statement block in your method and see if the error goes away. Try it like:

public void testMethod()
{
    using (DataTable dt = new DataTable())
    using (DataView dv = new DataView(dt))
    {
        //your work
    }
}
like image 156
Habib Avatar answered Sep 21 '22 16:09

Habib


From Dispose objects before losing scope

If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead.

To fix a violation of this rule, call System.IDisposable.Dispose on the object before all references to it are out of scope.

Note that you can use the using statement (Using in Visual Basic) to wrap objects that implement IDisposable. Objects wrapped in this manner will automatically be disposed at the close of the using block.

using (DataTable dt = new DataTable())
using (DataView dv = new DataView(dt))
{

}
like image 34
Soner Gönül Avatar answered Sep 20 '22 16:09

Soner Gönül