TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 by Deborah Kurata
 Aug 11, 2004
 Page 2 of 3

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

Mathematical Operators

To provide for the addition of two Price objects, you could define an Add method and pass it to two Price objects. But it would be more intuitive if you could simply add the two Price objects with the + operator. That is the purpose of operator overloading.

The code to overload an operator uses a static method with the operator keyword to define the method as an overloaded operator.
``````   public static Price operator +(Price p1, Price p2)
{
Price p3;
//Convert both currencies to a base currency
float p1InUSD = p1.Amount * p1.ExchangeRateWRTUSD;
float p2InUSD = p2.Amount * p2.ExchangeRateWRTUSD;

// Add the two prices in the base currency
// Convert the result to the first currency type
float p3Converted = (p1InUSD + p2InUSD) /
p1.ExchangeRateWRTUSD;
p3 = new Price(p3Converted,
p1.CurrencyCode,
p1.ExchangeRateWRTUSD);
}
return p3;
}
``````
This method converts each amount to the base currency (USD), adds the amounts, and then converts the result back to the currency of the first Price object.

You can make this method smarter. If the two exchange rates are the same, it could bypass the conversions.
``````   //If both exchange rates are the same type,
if (p1.ExchangeRateWRTUSD ==
p2.ExchangeRateWRTUSD)
{
p3 = new Price(p1.Amount+p2.Amount,
p1.CurrencyCode,
p1.ExchangeRateWRTUSD);
}
else
{
//Convert both currencies to a base currency
}
``````
You use the overloaded operator with your data type just like any other data type. Simply add Price objects together.
```

.qs-listings #asset-middle-b .group {
width: 70% !important;;
}

.qs-listings #bottomline {
width: 70% !important;
}

```   Price keyboardPrice =
new Price(40,"AUS",(float).6);
Price mousePrice =
new Price(20, "EUR", (float).8);
Price Total = keyboardPrice + mousePrice;
MessageBox.Show("Total Order Price is: " +
Total.Amount.ToString());
``````
You would use similar code to overload the -, *, and / operators. I'll leave that code as an exercise for the reader.

Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date