Mupp,
There are alot to memory management in .net. I assume, by the way you
are
expecting the destructors to work, that you are coming from a C++
background.
If so then here is where you forgett what you know about destructors in C++
since
they work completly different in .NET.
First of all lets have a look at what ~ClassName actually means to .net. If
you have
a class which looks like this
class Foo
{
~Foo ()
{
// ...
}
}
When you compile this, you will actually end up with
class Foo
{
protected override void Finalize ()
{
try
{
//. . .
}
finally
{
base.Finalize();
}
}
So it actually rolls out to a Finalize call. Now what about Finalizers? Well
the only
thing you really need to know about them are
* You don't know IF they will be called on your objects
* You don't know WHEN they will be called on your objects
* You don't know IN WHAT ORDER they will be called on your objects
Sounds great doesn't it? ;) There are a bounch of issues (by design) in the
GC which
is too "blame" for this. You could read
http://www.csharphelp.com/archives2/archive297.html
for more information on how GC works.
So why does your destructors get called in the order they do? Well first of
all it comes
down to the third point in the list - by concidense. What about the
reference you claim to
exsist between the objects? Well it does exist but since the only way you
can get to the
Contained object is through your Container object, and there is no referens
to the latter
object - your Contained object is deemed unreachable thus it is a candidate
for memory
management.
This has been a very short description what is going on and why. I recommend
you read
the above link (and perhaps a few more - search on google) to get an
understanding on
how the GC works.
HTH,
//Andreas
"mupp" <as**********@hotmail.com> skrev i meddelandet
news:65**************************@posting.google.c om...
I am wondering if someone could please explain the behaviour observed
in the following example:
class Contained
{
~Contained ()
{
}
}
class Container
{
Contained m_oContained;
public Container ()
{
m_oContained = new Contained ();
}
~Container ()
{
m_oContained = null;
}
}
Now create an instance of Container then immediately set to null so
that the newly created object is due for garbage collection e.g.:
Container l_oTest = new Container();
l_oTest = null;
What I don't understand is this: the Contained destructor is being
called BEFORE the Container destructor. This doesn't make sense to me
as a reference to the Contained object ( namely m_oContained ) still
exists when the Contained destructor is called. Indeed, when the
Container destructor is later called, the watch window reports
m_oContained as still referencing a valid object?!
Thanks in advance