Code Analysis CA2000

R

Raymon

This is driving me nuts.
I have a emthod that returns a DataTable.
The outline of the mothod is as follows:

public DataTable MyMethod(<argument list>)
{
DataTable dt = null;

try
{
dt = new DataTable;

(code to add columns to dt)


(Do lots of stuff)


return dt;
}
finally
{
if (dt != null)
dt.Dispose();
}

There is no catch block as the caller will handle any exceptions.

When I run code analysis I get the warning to the effect:
"call dispose on objec dt befor all references to it are out of scope"

There are several places in the try block (other than at the end)
where the code exits with a return dt.
But no matter what happens in the try block, even if an exception
occurs, the finally executes.
Isn't that correct?
Then why is it giving this warning?

The curious thing is that I use the same method of dispose in other
methods and they don't generate this warning.

P.S. Don't ask for the code as it is too long.
 
R

Registered User

This is driving me nuts.
I have a emthod that returns a DataTable.
The outline of the mothod is as follows:

public DataTable MyMethod(<argument list>)
{
DataTable dt = null;

try
{
dt = new DataTable;

(code to add columns to dt)


(Do lots of stuff)


return dt;
}
finally
{
if (dt != null)
dt.Dispose();
}

There is no catch block as the caller will handle any exceptions.

When I run code analysis I get the warning to the effect:
"call dispose on objec dt befor all references to it are out of scope"

There are several places in the try block (other than at the end)
where the code exits with a return dt.
But no matter what happens in the try block, even if an exception
occurs, the finally executes.
Isn't that correct?
Then why is it giving this warning?

The curious thing is that I use the same method of dispose in other
methods and they don't generate this warning.
Do the other methods return the instance that gets disposed? In the method above
the code the finally block gets executed before the method returns. Essentially
the code is saying destroy the object and then return the object.

<http://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx>

regards
A.G.
 
R

Rick Lones

Would not "return dt;" cause a reference to be created and placed wherever
references are returned? (I'm pretty sure the answer is yes.) If so, what is
the scope of that reference? (I don't know, but I'm sure someone can provide
chapter and verse from the spec.)

Would the above have anything to do with what your analyzer is flagging? It
seems at least plausible to me.

-rick-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top