Pierre Greborio.NET

Talking about .NET world

[Money Pattern] First step implementing money

Well, how much cash do I have in my pocket ? I can say 52.24 ! What ? Euro, US Dollars, Yen or whatever ? It's clear that indicate the money just as an amount isn't enought. But to indicate money like a combination of an amount and a symbol is too simplicistic. Just to start from somewhere I can create a Currency class which contains some info about the currency:

public class Currency
{
 public string Country;
 public string Name;
 public string ISOCode;
 public string Symbol;

 public Currency()
 {
  Country = "";
  Name = "Euro";
  ISOCode = "EUR";
  Symbol = "\u20AC";
 }

 public Currency(string isoCode)
 {
  ISOCode = isoCode;
 }

 public override string ToString()
 {
  return ISOCode;
 }

 public override int GetHashCode()
 {
  return ISOCode.GetHashCode();
 }

 public override bool Equals(object obj)
 {
  if (!(obj is Currency))
   return false;

  return (obj as Currency).ISOCode.Equals(this.ISOCode);
 }

 public static bool operator ==(Currency a, Currency b)
 {
  return a.Equals(b);
 }

 public static bool operator !=(Currency a, Currency b)
 {
  return !a.Equals(b);
 }
}

[I live in Euroland, then my default is Euro :-)]

Note that each currency is identified by their ISO 4217 currency codes. Now that we have the Currency we can create our Money:

public class Money
{
 private decimal _amount;
 private Currency _currency;

 public decimal Amount
 {
  get { return _amount; }
  set { _amount = value; }
 }

 public Currency Currency
 {
  get { return _currency; }
 }

 public Money()
 {
  _currency = new Currency();
 }

 public Money(decimal amount) : this()
 {
  _amount = amount;
 }

 // Continues here

Ok, we have a Money class, which contains all info we need. Then the instance of my money (on my pocket) is

Money money = new Money(52.24m);

That isn't enought, trust me. Next time I'll implement all other features...

Comments

Kevin said:

i'm looking forward to more features!

Kevin
# March 2, 2005 2:25 PM

TrackBack said:

# March 3, 2005 8:44 PM

Pierre Greborio said:

Kevin,
they will come soon :-)
# March 6, 2005 4:16 AM

TrackBack said:

# March 8, 2005 11:07 AM