5.4. Interfaces in .NET
The .NET Framework class library doesn't contain much in the way of interfaces, but every object designer should be familiar with a few of them. IDisposable is probably the most important because it plays an important role in garbage collection. Comparing and copying objects are also relatively common tasks; therefore, you should look at IComparable and ICloneable. ISerializable (discussed in Chapter 8) converts an object to a stream to persist it to disk or transport it across a network. Undoubtedly, though, constructing collections is one of the most essential programming tasks used in building object hierarchies. In .NET, collections are built by using IEnumerable and IEnumerator. These two interfaces allow your objects to be exposed through a For...Each loop, among other things.
As you have seen, the lifespan of an object is nondeterministic; there is no way to know when an object will be freed. At some given point, the garbage collector (GC) decides that an object is no longer in use and reclaims its memory. If the object has a Finalize method, the GC calls it; it acts as a rough analog to a destructor.
This scenario creates two problems. First, calling Finalize is expensive. Garbage collection runs twice for these objects. On the first pass, the GC puts all objects that implement Finalize into the finalization queue and frees everything else. On the second pass, it must call Finalize for all objects in the queue, and only ...