Deep/Shallow copy when returning objects (DataTable) from methods

B

bubby

Should I be concerned about the classic "Deep/Shallow" copy problem
when returning objects, specifically a DataTable or DataView from a
method? For example, see the code below:

private DataTable LoadStuff()
{
DataTable dt = new DataTable();
....
dt.Columns.Add(...)
....
dt.Rows.Add(...)

return dt;
}

Will the memory allocated within this function be valid outside of the
function after the return? Wouldn't the DataTable object need to
implement the ICloneable interface to perform a deep copy?

By contrast, how does this differ if I was using returning my own user
defined object instead the DataTable?

Thanks!
Andy
 
J

Jon Skeet [C# MVP]

bubby said:
Should I be concerned about the classic "Deep/Shallow" copy problem
when returning objects, specifically a DataTable or DataView from a
method? For example, see the code below:

private DataTable LoadStuff()
{
DataTable dt = new DataTable();
....
dt.Columns.Add(...)
....
dt.Rows.Add(...)

return dt;
}

Will the memory allocated within this function be valid outside of the
function after the return? Wouldn't the DataTable object need to
implement the ICloneable interface to perform a deep copy?

By contrast, how does this differ if I was using returning my own user
defined object instead the DataTable?

It wouldn't at all. You really need to get to grips with how reference
types and value types work, and how garbage collection works, before
you dive into things like ADO.NET.

See http://www.pobox.com/~skeet/csharp/parameters.html for details
about reference types etc. See
http://msdn.microsoft.com/msdnmag/issues/1100/GCI/default.aspx
for information about garbage collection.
 

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