Skip to content

Instantly share code, notes, and snippets.

@cbcwebdev
Created April 13, 2012 22:26
Show Gist options
  • Save cbcwebdev/2380551 to your computer and use it in GitHub Desktop.
Save cbcwebdev/2380551 to your computer and use it in GitHub Desktop.
/// <summary>
/// Represents a monetary amount for a given currency.
/// Allows easy representation and conversion of monetary values.
/// </summary>
public class Money
{
/// <summary>
/// Amount of money
/// </summary>
public readonly decimal Amount;
/// <summary>
/// Currency of money
/// </summary>
public readonly string CurrencyCode;
/// <summary>
/// Creates a representation of the designated
/// amount, using the current culture as currency.
/// </summary>
/// <param name="amount">Amount of money to represent</param>
public Money(decimal amount)
: this(amount, CultureInfo.CurrentCulture.Name)
{ }
/// <summary>
/// Creates a representation of the designated
/// amount for the provided currency.
/// </summary>
/// <param name="amount">Amount of money to represent</param>
/// <param name="currencyCode">Currency to represet money as</param>
public Money(decimal amount, string currencyCode)
{
Amount = amount;
CurrencyCode = currencyCode;
}
/// <summary>
/// Converts money from one currency to another. Keep in mind
/// this doesn't do an exchange rate, it simply converts the
/// representation to a different currency.
/// </summary>
/// <param name="currencyCode">Currency to represent new money as</param>
public Money Convert(string currencyCode)
{
return new Money(Amount, currencyCode);
}
/// <summary>
/// Formats money using the appropriate culture
/// </summary>
public override string ToString()
{
return Amount.ToString("C", CultureInfo.CreateSpecificCulture(CurrencyCode));
}
}
@cbcwebdev
Copy link
Author

could improve via Equals, GetHashCode, and static operator overloads

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment