I'v always thought that setting value to null means that it can be garbage
Incorrect. Objects become eligible for garbage collection when there are no
remaining references to them from other objects that are in use. If, for
example, you create an instance of a class within another class, such as a
Page, for example, the Page has a reference to the class in it. When the
Page is unloaded, the class has no more references to it, and is therefore,
available for Garbage Collection. Setting a variable to null does nothing to
the class it references, other than removing the reference to the class
coming from the variable. If the class is referenced by some other in-memory
object, it remains until all references are gone.
In order to understand this, it is important to understand the difference
between a variable (or field) and a class. A variable is a "handle," if you
will, to whatever it contains. For example:
object s; // Empty variable, points to nothing
s = SomeObject; // Assigns the object SomeObject to variable
s.
s = AnotherObject; // Assigns AnotherObject to variable s.
When SomeObject is assigned to s, s IS NOT SomeObject, but a "handle" that
enables you to use SomeObject via s.
When AnotherObject is assigned to s, it is no longer referencing SomeObject.
Where is SomeObject? Still in memory, but referenced by no other objects. It
is therefore available to GC.
If s is in a function, when that function is pulled off the stack, s is
pulled with it, and whatever object it is referencing is no longer bound to
anything, and is therefore, available to CG.
If s is in a class instance, when that class instance is de-referenced, s is
pulled off the stack with the class instance, and whatever object it is
referencing is no longer bound to anything, and is therefore, available to
GC.
--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living