Overloading Operators in VB.NET 2.0

Although you do not need to write overloaded operators every day, this feature certainly puts the latest version of VB.NET (whether you call it 2.0 or 8.0there is some confusion in this area) on par with even the most powerful object-oriented languages. This article demonstrates a step-by-step process for writing custom operators, including a brief explanation for neophytes. Of course, if you didn't like VB.NET because of its differences from VB6, you probably won't get too excited about the ability to overload operators in VB.NET 2.0.

What Operators Are and Why You Overload Them

Programming has a rich history based in mathematics. Mathematics is steeped in meaningful symbols, operators, and operands. Operators are symbols that perform a function and operands are the things on which operators operate.

Operators typically indicate how many operands they use. Usually, you'll encounter unary, binary, and ternary operators. Unary means one operand, binary means two, and ternary means three. "Not" is an example of a unary operator; "+" is an example of a binary operator; and "?:" is an example of a ternary operator. (I have never seen a quaternary operator.)

Operators are convenient because they are quick to write and they are familiar, especially in arithmetic operations. For example, "&" and "+" are Boolean and arithmetic operators, but you can also used them to perform string concatenation for string operands. Clearly, operators have had multipleor overloadedmeanings for some time. A natural evolution is this ability extending to us programmers.

Basic Guidelines for Overloading Operators

You should follow a few basic guidelines for overloading operators to either get past the compiler or avoid confusing people:

Don't change an operator's semantic meaning. The result of an operator should be intuitive.

Make certain overloaded operators are shared methods.

Overload operators in pairs, if a symmetric pair exists. These are the pairs of operators: "=" and "<>"; ">" and ">"; ">=" and "<="; and IsTrue and IsFalse.

You cannot overload assignment (for example, the "=" operator in the preceding guideline is the equality-test operator.).

You can overload only the operators listed in Table 1.

Table 1: Operators That Can Be Overloaded in .NET 2.0

Operator

Operand Count

Description

+

Unary

Positive

-

Unary

Negative

IsFalse

Unary

Is False test

IsTrue

Unary

Is True test

Not

Unary

Negation

+

Binary

Addition

-

Binary

Subtraction

*

Binary

Multiplication

/

Binary

Floating-point division

\

Binary

Integer division

&

Binary

Concatenation

^

Binary

Exponentiation

>>

Binary

Shift right

<<

Binary

Shift left

=

Binary

Equality; assignment cannot be overloaded

<>

Binary

Not equal

>

Binary

Greater than

<

Binary

Less than

>=

Binary

Greater than or equal to

<=

Binary

Less than or equal to

And

Binary

Bitwise and

Like

Binary

String pattern matching

Mod

Binary

Modulo division

Or

Binary

Bitwise or

Xor

Binary

Bitwise xor

CType

Unary

Type conversion

Finally, don't assume that operators have been overloaded correctly or that others have defined all possible operators.

Defining a Named Method

Generic methods in VB.NET must be shared. They must have the same number of arguments as your operator will have. Thus, if you are overloading addition, you need a shared method with two arguments and a return type.

Suppose your problem domain needs a distance measured in feet and inches. (Don't worry; you could localize this class to switch to metric units, but that isn't relevant to this discussion.) To support your problem domain, you could easily define a class Distance that stores feet and inches as integers (see Listing 1).

Listing 1 converts all inches greater or equal to 12 to feet. For example, if you set the inches field using the Inches property, 14 inches becomes 1 foot, 2 inches. Next, you can support basic arithmetic operations by defining addition and subtraction. Following your named methods guidelines, you get the named methods in Listing 2.

Overloading Operators in VB.NET 2.0

Defining an Operator Method

At this point, you have your new class: Distance. You have defined fields, properties, and named methods for operations you'd like to perform on your class. Finally, you can create the operator methods by copying and pasting the named methods and changing the keyword Function to Operator and the method name to operator(symbol), where operator is a literal and symbol represents the actual operator (in this example, "+" and "-"). To complete the implementation, simply call the named methods in the operator methods. Listing 3 shows the additional operator methods.

Tip: If you are very comfortable with operator overloading, skip the create named methods step. As for me, after 16 years of OOP programming, this is still a useful technique.

Listing 4 shows the entire listing of the Distance class and a Main method in a Console application to show you how to invoke the overloaded operators. In this example, "+" and "-" work as you would expect.

Listing 4: The Distance Class with Overloaded Operators and a Sample Main Subroutine

Intuitive Operators for Your Classes

Operator overloading is harder in C++ because C++ supports overloading tricky member-of operators like member-of (.) and function call (). In addition, C++ supports static and instance operators, but using name methods makes overloading even esoteric operators like () easier.

In VB.NET (and C#), overloaded operators must be shared (static), and operator methods must have the same count as the operator you are overloading. Finally, in VB.NET the special word Operator is used in place of Sub or Function, which makes it very clear that the method you are looking at is an operator statement.

Overloading operators can provide your classes with intuitive operators, and they are easy to implement and use, as long as you don't change the underlying behavior of the operator and use named methods to separate syntax from implementation.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his upcoming book UML DeMystified from McGraw-Hill/Osborne (Spring 2005) and Expert One-on-One Visual Studio 2005 from Wrox (Fall 2005). Paul is also the founder and chief architect for Software Conceptions, Inc, founded 1990. He is available to help design and build software worldwide. You may contact him for consulting opportunities or technology questions at pkimmel@softconcepts.com.

If you are interested in joining, sponsoring a meeting, or posting a job, check out www.glugnet.org, the Web page of the Greater Lansing area Users Group for .NET.

Data integrity and ultra-high performance dictate the success and growth of many companies.
One of these companies is BridgePay Network Solutions, a recently launched and rapidly growing financial services organization that allows merchants around the world to process millions of daily credit card transactions. Due to the nature of their business, their IT team needed to strike the perfect balance between meeting regulatory-mandated data security measures with the lowest possible levels of latency and …