- 1 A First C# Program
- 2 Namespaces
- 3 Alternative Forms of the Main() Function
- 4 Making a Statement
- 5 Opening a Text File for Reading and Writing
- 6 Formatting Output
- 7 The string Type
- 8 Local Objects
- 9 Value and Reference Types
- 10 The C# Array
- 11 The new Expression
- 12 Garbage Collection
- 13 Dynamic Arrays: The ArrayList Collection Class
- 14 The Unified Type System
- 15 Jagged Arrays
- 16 The Hashtable Container
- 17 Exception Handling
- 18 A Basic Language Handbook for C#
1.12 Garbage Collection
We do not explicitly delete objects allocated through the new expression. Rather, these objects are cleaned up by garbage collection in the runtime environment. The garbage collection algorithm recognizes when an object on the managed heap is no longer referenced. That object is marked as available for collection.
When we allocate a reference type on the managed heap, such as the following array object:
int [] fib = new int[6]{ 1,1,2,3,5,8 };
the heap object is recognized as having an active reference. In this example, the array object is referred to by fib.
Now let's initialize a second array handle with the object referred to by fib:
int [] notfib = fib;
The result is a shallow copy. Rather than notfib addressing a separate array object with its own copy of the six integer elements, notfib refers to the array object addressed by fib.
If we modify an element of the array through notfib, as in
notfib [ 0 ] = 0;
that change is also visible through fib. If this sort of indirect modification (sometimes called aliasing) is not acceptable, we must program a deep copy:
// allocate a separate array object notfib = new int [6]; // copy the elements of fib into notfib // beginning at element 0 of notfib fib.CopyTo( notfib, 0 );
notfib no longer addresses the same array object referred to by fib. If we now modify an element of the array through notfib, the array referred to by fib is unaffected. This is the semantic difference between a shallow copy and a deep copy.
If we now reassign fib to also address a new array objectfor example, one that contains the first 12 values of the Fibonacci sequence:
fib = new int[12]{ 1,1,2,3,5,8,13,21,34,55,89,144 };
the array object previously referred to by fib no longer has an active reference. It may now be marked for deletionwhen and if the garbage collector becomes active.