summaryrefslogtreecommitdiff
path: root/lib/quantity.cs
blob: 56fd55c1815e39f581cc263e861102a9ba8063d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Quantity
{
  decimal amount;
  UnitOfMeasure unit;

  public Quantity(decimal amount, UnitOfMeasure unit)
  {
    this.amount = amount;
    this.unit = unit;
  }

  public Quantity convert_to(UnitOfMeasure unit)
  {
    return new Quantity(unit.convert(this.amount, this.unit), unit);
  }

  public Quantity plus(Quantity other)
  {
    var converted = other.convert_to(this.unit);
    return new Quantity(this.amount + converted.amount, this.unit);
  }

  public Quantity subtract(Quantity other)
  {
    var converted = other.convert_to(this.unit);
    return new Quantity(this.amount - converted.amount, this.unit);
  }

  public bool Equals(Quantity other)
  {
    if (ReferenceEquals(null, other)) return false;
    if (ReferenceEquals(this, other)) return true;
    return other.amount.Equals(amount) && Equals(other.unit, unit);
  }

  public override bool Equals(object obj)
  {
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    if (obj.GetType() != typeof (Quantity)) return false;
    return Equals((Quantity) obj);
  }

  public override int GetHashCode()
  {
    unchecked
    {
      return (amount.GetHashCode()*397) ^ (unit != null ? unit.GetHashCode() : 0);
    }
  }

  public override string ToString()
  {
    return this.amount.ToString() + " " + this.unit.ToString();
  }
}