Content by Category
.NET 1.x
.NET 2.0
.NET 3.0
.NET 3.5
.NET 4.0
.NET Assemblies
.NET Framework
.NET Getting Started
Accessibility
ADO.NET
Advertorials
Agile Development
AJAX
Architecture
ASP.NET
ASP.NET MVC
ASP.NET WebForms
Azure
B2B (Business Integration)
Bing
BizTalk
Book Excerpts
Build and Deploy
C#
C++
ClickOnce
Cloud Computing
Code Contracts
CODE on the Road!
COM+
Community
Conferences
Continuous Integration
Crystal Reports
CSLA.NET
CSS
Data
Design Patterns
Development Process
Display Technologies
Distributed Computing
DotNetNuke
DSL
Dynamic Programming
Editorials
Enterprise Services ("COM+")
Entity Framework
Events
Expression Blend
F#
Fox to Fox
Frameworks
Functional Programming
Git
Graphics
Internet Explorer 8.0
Interviews
iPhone
Iron Ruby
Java
Java Script
jQuery
LINQ
Linux
Mac OS X
MDX
Microsoft Application Blocks
Microsoft Business Rules Framework
Microsoft Dynamics
Microsoft Expression
Microsoft Office
Mobile Development
Mobile PC
Mono
MsBuild
Network
NHibernate
Object Oriented Development
Odata
Open Source
Opinion
Opinions
Oracle
ORM
Other Languages
Parallel Programming
Patterns
Podcasts
Post Mortem
PowerPoint
Print/Output
Prism
Product News
Product Reviews
Project Management
Python
Q&A
Rails
Rake
Reporting Services
REST
RIA Services
Ruby
Ruby on Rails
Search
Security
Services
SharePoint
Silverlight
SOA
Social Networks
Software & Law
Software Business
Source Control
Speech-Enabled Applications
SQL Server
SQL Server 2000
SQL Server 2005
SQL Server 2008
SQL Server CE/AnyWhere/Mobile/Compact
SSIS
Subversion
Sync Framework
Tablet PC
TDD
Team System
Techniques
Testing and Quality Control
Tips
UI Design
UML
User Groups
VB Script
VB.NET
Version Control
VFP and .NET
VFP and SQL Server
Virtual Earth
Vista
Visual Basic
Visual Basic 6 (and older)
Visual FoxPro
Visual Studio .NET
Visual Studio 2005
Visual Studio 2008
Visual Studio 2010
Visual Studio Tools for Office
VSX
WCF
Web Development (general)
Web Services
WF
Whitepapers
Windows 7
Windows Azure
Windows Live
Windows Server
Windows Vista
WinForms
Workflow
WPF
XAML
XML
XNA
XSLT



INSTANTLY dtSearch® TERABYTES OF TEXT


 


INSTANTLY dtSearch® TERABYTES OF TEXT

Reader rating:
Click here to read 3 comments about this article.
Article source: CoDe (2004 - July/August)


Article Pages:  1  2 - Next >


Overload Operators to Operate on Your Objects

Operator overloading provides an intuitive way to support mathematical and comparative operations on your objects.Operator overloading is one of those features that you don't need very often, but when you need it, operator overloading is very nice to have. You will find operator overloading in C# now, but you won't find it in Visual Basic until the upcoming Visual Studio 2005 release.

Operator overloading allows you to define mathematical and comparative operators for your data types. Objects created with your data type can then be manipulated mathematically or compared using standard operators.

Foreign Currency Price Example

As an example, a Price data type, which supports amounts in any currency, overloads the mathematical operators to allow mathematically manipulating prices in different currencies. In today's global economy, this is a useful feature.

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

The Price data type in this example is a structure comprised of several fields. The Amount field defines the price amount in a defined currency. The CurrencyCode field is the three-character code for the currency, such as USD (U.S. dollars), AUD (Australian dollars), or EUR (European Euro).

In a production-level application, the Amount and CurrencyCode fields would be enough. The application would use the CurrencyCode to look up the appropriate currency exchange rates in a table (if current currency rates aren't a requirement) or from a service (if current exchange rates are a requirement).

But writing lookup tables or accessing a service takes away from the focus of this column: operator overloading. So instead, the Price data type in this example has a third field for the exchange rate.

As you know, every currency has an exchange rate with respect to every other currency. The standard way to operate on two prices defined with two different currencies is to find the exchange rate between the two currencies, convert one currency to the other, and then perform the operation. This allows you to add "apples and apples" as the saying goes.

However, any one particular Price object in this example would not know what other currency it may need to convert to. So it could not store just one exchange rate, it would need to store an exchange rate for every possible other currency.

A better approach is to define a base currency. Every Price object stores the exchange rate with respect to the base currency. The application then converts each Price amount to the base currency, performs the operation, and converts back to the desired currency. This example selected USD as the base currency, but you can use any currency for this purpose.

The structure below defines the three fields of the Price data type.

public struct Price
{
    public float Amount;
    public string CurrencyCode;
    public float ExchangeRateWRTUSD;
}

The constructor for this structure sets the values of the fields:

public Price(float fAmount, string sCurrencyCode,
             float fExchangeRateWRTUSD)
{
    this.Amount = fAmount;
    this.CurrencyCode=sCurrencyCode;
    this.ExchangeRateWRTUSD = fExchangeRateWRTUSD;
}

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.

&

By: Deborah Kurata

Deborah Kurata is cofounder of InStep Technologies Inc., a professional consulting firm that focuses on turning your business vision into reality using Microsoft .NET technologies. She has over 15 years of experience in architecting, designing and developing successful applications.

Deborah is the author of several books, including Best Kept Secrets in .NET (Apress), Doing Objects in Visual Basic 6.0 (SAMS) and Doing Web Development: Client-Side Techniques (Apress). She is on the INETA Speaker’s Bureau, is a well-known speaker at technical conferences, and is a Microsoft Most Valuable Professional (MVP). After a hard day of coding and taking care of her family, Deborah enjoys blowing stuff up (on her XBox of course).

Some of the information in this article was obtained from her upcoming book, Doing Objects in VB 2005.

deborahk@insteptech.com

Fast Facts

Operator overloading allows you to use standard operators, such as + and >, with your own data types.



Article Pages:  1  2 - Next Page: 'Assignment Operators' >>

Page 1: Overload Operators to Operate on Your Objects
Page 2: Assignment Operators

How would you rate the quality of this article?
1 2 3 4 5
Poor      Outstanding

Tell us why you rated the content this way. (optional)

Average rating:
2.7 out of 5

7 people have rated this article.

      DevConnections

 

QCon