I have this in my main:
static void Main(string[] args)
{
Money m1 = new Money(2315.99);
Money m2 = new Money(4000, 25);
Console.WriteLine(m1);
Console.WriteLine(m2);
Console.WriteLine(m1.IncrementMoney(m2));
}
public void IncrementMoney(Money x)
{
//what do I put in here?
}
So
Money m1 = new Money(2315.99);
is supposed to turn 2315.99 into “$2315.99”
and
Money m2 = new Money(4000, 25);
forms “$4000.25”
I have all that done in Money class and it works fine.
Now what I’m supposed to do is add those two together using
m1.IncrementMoney(m2);
This is my “Money” class
class Money
{
//instance variables
private int dollars;
private int cents;
double amount;
public int Dollars
{
get { return dollars; }
set
{
if (value > 0)
dollars = value;
}
}
public int Cents
{
get { return cents; }
set
{
if (value > 0)
cents = value;
}
}
public Money(int Dol, int Cen)
{
Dollars = Dol;
Cents = Cen;
double Dollar = Convert.ToDouble(Dollars);
double Cent = Convert.ToDouble(Cents);
amount = Dollar + (Cent / 100);
}
public Money(double am)
{
int dol = Convert.ToInt32(am);
if (dol > am)
Dollars = dol - 1;
else if (dol < am)
Dollars = dol;
//Dollars
double cen = am % 1;
cen = cen * 100;
Cents = Convert.ToInt32(cen);
//Cents
double Dollar = Convert.ToDouble(Dollars);
double Cent = Convert.ToDouble(Cents);
amount = Dollar + (Cent / 100);
}
//override ToString()
public override string ToString()
{
return string.Format("{0:c}", amount);
}
}//end class Money
But I have no idea what to put into the IncrementMoney method.
Please help?
and if not too much trouble, maybe a little insight to how it works? I’d really like to know.
Sorry if I didn’t give enough info,
If anything else is required please let me know.
and thanks!
Since
IncrementMoneyis supposed to add the two money values together, your usage looks like it should instead be an extension method of theMoneytype. Which is fine, because extension methods are pretty awesome. A common joke on this site is that they’re the solution to everything.Your code should look similar to:
As for a quick explanation…
By adding
thisto the first argument, we are telling C# that we want to write an extension method. This will mean that this method we’re writing will hang off the type of thethisargument (in this case,Money) and allow us to use it exactly like it was always in the .NET framework. Extension methods have to be static, so you can’t not use that modifier. Beyond that, you just write a method to do whatever you have in mind, exactly like you normally would!I would suggest you name it something other than
IncrementMoney, though. That’s not very descriptive.AddMoneywould be better.You may also look into operator overloading, by the way. You could adapt what I just wrote to simply use the
+operator to do exactly the same thing, like so:With this defined, you can simply go
m1 + m2and add them together.