Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Overload Operators to Operate on Your Objects : Page 2

Operator overloading provides an intuitive way to support mathematical and comparative operations on your objects.


advertisement
Mathematical Operators
By overloading mathematical operators, such as +, -, and * for your data types, developers can add, subtract, multiply, or divide objects created with your data type.

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, //just add them 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.


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.

 

 

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