|
public void Push(object o) { public void Push (object o) { first = new Node(o, first); }
class Node { public Node Next; public object Value; public Node(object value) ; this (value, null) {} public Node(object value, Node net) { Next=nest; Value=value; } } }
|
The above program shows a Stack class implemented as a linked of Node instances. Node instances are created in the push Method and are garbage collected when no longer needed. A Node instance becomes ineligible for garbage collection when it is no longer possible for any code to access it. When an item is removed from the stack, the associated node instance becomes ineligible for garbage collection.
Following Program shows a test program that uses the stack class:
Class Test { Static void Main() { Stack s = new Stack (); For (int i=0;i<10;i++) s.Push(i); while (!s.Empty) console.WriteLine(s.Pop()); } } |
A Stack is created and initialized with 10 elements, and then assigned the value null. Once the variable's' is assigned null, the Stack and the associated 10 Node instances become eligible for garbage collection. The Garbage collector is permitted to clean up immediately, but is not required to do so.