Jon Skeet [C# MVP] wrote:
dm_dal <RE******************@yahoo.com> wrote:
Just a quick question regarding object scope and lifetime.
Given the following:
{
DataRow myRow = new DataRow();
...... do some stuff
{
myRow = new DataRow;
..... do some stuff
}
myRow = new DataRow;
..... do some stuff
}
Have I just created three seperate DataRow objects? Or does the assignment
just reassign the original?
You've created three separate DataRow objects. If you don't pass them
around in some way which keeps a reference elsewhere, each will become
eligible for garbage collection at the time when the next one's
reference is assigned to myRow. (That doesn't mean they'll be collected
immediately, however.)
To expand on this a bit...
Strictly speaking, an object referenced by myRow might become eligible
for collection *before* it gets assigned a new object reference. That
can happen if the JIT/Garbage Collector determines that the current
myRow reference is not used at some point before the re-assignment.
For example:
DataRow myRow = new DataRow();
// a) do some stuff
object o = myRow[0]; // get column 0's value
// b) do some other stuff, but not using myRow
myRow = new DataRow;
At any point after execution of the "object = = myRow[0];" statement
(section 'b') the object referenced by myRow can be collected - the GC
doesn't need to wait until the second assignment to myRow.
Normally, this isn't a problem (and I imagine it would not be with the
DataRow object), but I've seen some problems described in the news
groups that were a result of this kind of thing (one was a mutex
intended to signal new instances of the application that never seemed to
function, and the other was a Registry value write that blew up because
the underlying handle got closed by a finalizer called too early).
These problems can be real head scratchers if you don't realize that
object lifetime can be shorter than what you'd guess. I believe that
this issue would only be a true potential problem for objects that have
a finalizer.
Anyway, this is discussed by Chris Brumme in gory detail here:
http://blogs.msdn.com/cbrumme/archiv.../19/51365.aspx
--
mikeb