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

  • Thread starter Thread starter bubby
  • Start date Start date
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
 
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.
 
Back
Top