Home > Articles > Programming > Windows Programming

Hello, C#

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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 object—for 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 deletion—when and if the garbage collector becomes active.

  • + Share This
  • 🔖 Save To Your Account