Home   Cover Cover Cover Cover
 

IDumpable interface

/csbook/solutions/10/A04.cs
using System;

interface IDumpable {
  string Name { get; set; }
  void Dump();
}

class Fraction: IDumpable {
  int z, n;
  string name;
  
  public Fraction(int z, int n) {
    this.z = z; this.n = n;
  }
  
  public string Name {
    get { return name; }
    set { name = value; }
  }
  
  public static Fraction operator + (Fraction a, Fraction b) {
    return new Fraction(a.z * b.n + a.n * b.z, a.n * b.n);
  }
    
  public static Fraction operator * (Fraction a, Fraction b) {
    return new Fraction(a.z * b.z, a.n * b.n);
  }
  
  public int CompareTo(object obj) {
    Fraction f = (Fraction)obj;
    if ((float)z/n < (float)f.z/f.n) return -1;
    else if ((float)z/n > (float)f.z/f.n) return 1;
    else return 0;
  }
  
  public void Dump() {
    Console.WriteLine("Fraction: " + z + "/" + n);
  }
}

class Person: IDumpable {
  string name;
  public string address;
  public int phone;
  
  public Person(string name, string address, int phone) {
    this.name = name; this.address = address; this.phone = phone;
  }
  
  public string Name {
    get { return name; }
    set { name = value; }
  }
  
  public void Dump() {
    Console.WriteLine("Person: {0}, {1}, {2}", name, address, phone);
  }
}

class Test {
  
  static void Main(string[] arg) {
    IDumpable[] a = {
      new Fraction(3,5),
      new Fraction(8,3),
      new Person("John", "San Francisco", 7403814),
    };
    a[0].Name = "f1";
    a[1].Name = "f2";
    foreach (IDumpable obj in a) {
      Console.Write(obj.Name + ": ");
      obj.Dump();
    }
  }
  
}