Cor Ligthert said:
I think you are wrong, however it does nothing add to the question from
the
OP.
I can't easily prove that strings behave differently to other objects
(we could use the .NET performance counters, but it's hard to do in
other ways), but I *can* prove that an object can be garbage collected
before a variable referencing it falls out of scope. Try the following
program, compiled with optimisation enabled and debug disabled:
using System;
class Test
{
~Test()
{
Console.WriteLine ("I'm being finalized");
}
static void Main()
{
Test x = MakeTest();
// Do some work which uses a lot of memory
long y=0;
for (int i=0; i < 1000000; i++)
{
byte[] b = new byte[10];
y += b.Length;
}
// Just keep the compiler honest...
Console.WriteLine (y);
Console.WriteLine ("The method still hasn't finished...");
}
static Test MakeTest()
{
return new Test();
}
}
On my box, the output is:
I'm being finalized
10000000
The method still hasn't finished...
Now, I suppose you *could* try to argue that even though the object is
clearly being finalized, it may not have been garbage collected - but
it seems pretty unlikely that the GC would go to the trouble of
finalizing an object if it didn't want to actually collect it.
In my opinion was the reply from Marina more than enough,
Except that it's not the whole story. It's important to understand that
things can be eligible for garbage collection before they fall out of
scope. People have been caught out before due to this, for instance
using a mutex to make sure there's only one instance of the application
running: if the mutex is finalized and then garbage collected before
they expect it to be, that can mean the program behaves unexpectedly.
So I stop this discussion.
Well, you've claimed that I'm wrong about something, and I'd appreciate
you backing that up with some evidence. I've backed up my side of
things above. It's not like this is a matter of opinion, and it *is*
important that people reading this thread can get a definitive answer -
it can easily affect whether or not they write correct code, as shown
above.