I have this code:
Essentially i\'m trying to demonstrate the use of the c# finalizer and make an object that cannot die, I called it Zombie. Now, normally this demo
EDIT: While the original answer below is still accurate, it looks like it's the mixture of debug information and optimization which makes a difference here.
From my experiments:
Compiler flags Result
/o+ /debug- Finalizer runs
/o+ /debug+ Finalizer runs
/o- /debug- Finalizer runs
/o- /debug+ Finalizer does *not* run
The finalizer is still called on my box, when compiling on the command line with /o+
. My guess is that you're running in a debugger - which changes the GC behaviour. Without the debugger, the GC will collect anything that it can prove will never be read. With the debugger, I believe the GC won't collect any objects which still have references on the stack, even if there's no code to read the variables in question.
Now with an object initializer, the compiler code includes an extra reference on the stack. This line:
Zombie z = new Zombie { Name = "Guy" };
is effectively:
Zombie tmp = new Zombe();
tmp.Name = "Guy";
Zombie z = tmp;
The assignment to z
is only performed after all the properties have been set.
My guess is that the tmp
variable here is keeping the object alive.
If you want objects that don't die, you really don't need to mess with finalizers. Just have a private static list of all instances, and add objects to that list as they are created:
class Immortal
{
static List<Immortal> _immortals = new List<Immortal>();
public Immortal()
{
_immortals.Add(this);
}
}