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();
}
}
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
}
}
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))
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With