Home   Cover Cover Cover Cover
 

Structs and properties

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

struct Time {
  int seconds;
  
  public Time(int h, int m, int s) {
    seconds = (3600 * h + 60 * m + s) % 86400;
  }
  
  public Time(int s) {
    seconds = s;
  }
  
  public int Hrs {
    get { return seconds / 3600; }
  }
  
  public int Min {
    get { return seconds % 3600 / 60; }
  }
  
  public int Sec {
    get { return seconds % 60; }
  }
  
  public static Time operator + (Time a, Time b) {
    return new Time(a.seconds + b.seconds);
  }
  
  public static Time operator - (Time a, Time b) {
    int sec = a.seconds - b.seconds;
    if (sec < 0) sec += 86400;
    return new Time(sec);
  }
  
  public static bool operator == (Time a, Time b) {
    return a.seconds == b.seconds;
  }
  
  public static bool operator != (Time a, Time b) {
    return a.seconds != b.seconds;
  }
  
  public override bool Equals(object obj) {
    return this == (Time)obj;
  }
  
  public override int GetHashCode() {
    return seconds;
  }
  
  public override string ToString() {
    return Hrs + ":" + Min + ":" + Sec;
  }
}

class Test {
  
  public static void Main() {
    Time a = new Time(3, 30, 00);
    Time b = new Time(17, 55, 20);
    Time c = a + b;
    Time d = a - b;
    Console.WriteLine("a = {0}, b = {1}, c = {2}, d = {3}", a, b, c, d);
  }
}