summaryrefslogtreecommitdiffstats
path: root/tools/NUnit/samples/csharp/money/Money.cs
blob: 2e2de939ca089e943812cb87b4001dc0e3bd3a10 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org/?p=license&r=2.4.
// ****************************************************************

namespace NUnit.Samples.Money 
{

	using System;
	using System.Text;

	/// <summary>A simple Money.</summary>
	class Money: IMoney 
	{

		private int fAmount;
		private String fCurrency;
        
		/// <summary>Constructs a money from the given amount and
		/// currency.</summary>
		public Money(int amount, String currency) 
		{
			fAmount= amount;
			fCurrency= currency;
		}

		/// <summary>Adds a money to this money. Forwards the request to
		/// the AddMoney helper.</summary>
		public IMoney Add(IMoney m) 
		{
			return m.AddMoney(this);
		}

		public IMoney AddMoney(Money m) 
		{
			if (m.Currency.Equals(Currency) )
				return new Money(Amount+m.Amount, Currency);
			return new MoneyBag(this, m);
		}

		public IMoney AddMoneyBag(MoneyBag s) 
		{
			return s.AddMoney(this);
		}

		public int Amount 
		{
			get { return fAmount; }
		}

		public String Currency 
		{
			get { return fCurrency; }
		}

		public override bool Equals(Object anObject) 
		{
			if (IsZero)
				if (anObject is IMoney)
					return ((IMoney)anObject).IsZero;
			if (anObject is Money) 
			{
				Money aMoney= (Money)anObject;
				return aMoney.Currency.Equals(Currency)
					&& Amount == aMoney.Amount;
			}
			return false;
		}

		public override int GetHashCode() 
		{
			return fCurrency.GetHashCode()+fAmount;
		}

		public bool IsZero 
		{
			get { return Amount == 0; }
		}

		public IMoney Multiply(int factor) 
		{
			return new Money(Amount*factor, Currency);
		}

		public IMoney Negate() 
		{
			return new Money(-Amount, Currency);
		}

		public IMoney Subtract(IMoney m) 
		{
			return Add(m.Negate());
		}

		public override String ToString() 
		{
			StringBuilder buffer = new StringBuilder();
			buffer.Append("["+Amount+" "+Currency+"]");
			return buffer.ToString();
		}
	}
}