Tuesday, 2 November 2010

Disposable Panda

// The instance field Name pertains to an instance of a particular Panda,
// whereas Population pertains to the set of all Pandas:

public class Panda : IDisposable{
  public string Name;                     // Instance field
  public static int Population;           // Static field
  public Panda (string n){                // Constructor
    Name = n;                             // Assign the instance field
    Population = Population + 1;          // Increment the static Population field
  void IDisposable.Dispose(){
    Population = Population - 1;          // Decrement the static Population field

static void Main(){
  Panda p1 = new Panda ("Pan Dee");
  Console.WriteLine (p1.Name);            // Pan Dee
  Console.WriteLine (Panda.Population);   // 1
  using(Panda p2 = new Panda ("Pan Dah")){
    Console.WriteLine (p2.Name);          // Pan Dah
    Console.WriteLine (Panda.Population); // 2
  Console.WriteLine (Panda.Population);   // 1
  Panda p3 = new Panda ("Zi Chi");
  Console.WriteLine (p3.Name);            // Zi Chi
  Console.WriteLine (Panda.Population);   // 2

I'm working through the examples in C# 4.0 in a Nutshell, Fourth Edition and I got to thinking about how to erase an instance of a class... using seemed to be the way to go so I implemented the IDisposable Interface and now I've got disposable Pandas!