Introduction to Operator Overloading in VB.NET
August 30th, 2007
Operator overloading has been around quite some time in object oriented languages like C++ but it’s a new feature in VB.NET with the .NET Framework 2.0. In this article, we’ll look at what operator overloading is and how we can use it in our VB.NET programs.
What is Operator Overloading?
Operator overloading is a type of polymorphism that applies to operators, like plus (+) or equals (=), and gives them different implementations. Using it you can redefine overloadable operations within your classes and structures and make your code cleaner and easier to read. It will also make it easier for you to interact with object that already expose overloaded operators.
Which VB.NET Operators Can Be Overloaded?
VB.NET allows the following operators to be overloaded:
- + (increment/plus - unary and binary)>
- - (decrement/minus - unary and binary)
- Not (unary)
- IsTrue (unary)
- IsFalse (unary)
- CType (unary)
- * (multiply - binary)
- / (divide - binary)
- \ (integer divide - binary)
- & (concatinate - binary)
- Like (binary)
- Mod (binary)
- And (binary)
- Or (binary)
- Xor (binary)
- ^ (raise to power - binary)
- << (left shift - binary)
- >> (right shift - binary)
- = (equals - binary)
- <> (not equals - binary)
- < (less than - binary)
- > (greater than - binary)
- <= (less than or equal to - binary)
- >= (greater than or equal to - binary)
Unary operators only have one argument while binary operators require two. Obvious, I know, but some novices stumble on this at first.
You don’t have to overload all of the operators in your class, just use the ones you need. However, you must include overloads for these logical pairs of comparative operators :
- = and <>
- < and >
- <= and >=
- IsTrue and IsFalse
How Do You Code It?
‘Operator’ is a method keyword just like Function and Sub. The difference is that the name you use is simply the operator as seen here:
Public Shared Operator +(ByVal message1 As EmailMessage, ByVal message2 As EmailMessage) As EmailMessage
Dim ReturnValue As New EmailMessage
'code here to combine objects into new object
Return ReturnValue
End Operator
Operators must always be declared as Shared and must always return a value. You cannot use an Exit statement with them, you must always use return. Another consideration is that the parameters or the return value must be the same as the containing class. For unary operators, the single parameter must be the containing class although the return value doesn’t have to be. For binary operators, at least one of the parameters must be the containing class.
Our code for calling the operator is quite simple, as seen here:
Dim OperationsAlertEmail As New EmailMessage Dim SalesAlertEmail As New EmailMessage 'Build Alert Emails here 'Combine them for executive distribution Dim ExecutiveAlertEmail As EmailMessage = OperationsAlertEmail + SalesAlertEmail
Also, you can have overloads to your binary operators. For example, let’s assume that in our example we have different classes for each type of email but we want to be able to combine them in some cases. Therefore we might have a set of overloaded operator methods like so:
Public Shared Operator +(ByVal message1 As SalesEmailMessage, ByVal message2 As ExecutiveEmailMessage) As ExecutiveEmailMessage
Dim ReturnValue As New ExecutiveEmailMessage
'code here to combine objects into new object
Return ReturnValue
End Operator
Public Shared Operator +(ByVal message1 As OperationsEmailMessage, ByVal message2 As ExecutiveEmailMessage) As ExecutiveEmailMessage
Dim ReturnValue As New ExecutiveEmailMessage
'code here to combine objects into new object
Return ReturnValue
End Operator
As mentioned above, only one of the parameters in a binary operation have to be of the containing type. This can allow you to code something like this:
Public Shared Operator &(ByVal message1 As EmailMessage, ByVal messageText As String) As String
Return message1.MessageHeader & message1.MessageText & messageText
End Operator
...................
Dim NewMessageText As String = ExecutiveAlertEmail & txtUpdatedMessage.Text
As you can see, using an overloaded operator can make it easy for your class to combine with other objects. In the example above, if the operator wasn’t there the concantination operation wouldn’t compile due to an “Operator Not Defined” error. While our example is rather simple, remember that you can expand this concept to encompass more complex solutions.
However, you do want to avoid any unnecessary complexity in your operator code. Don’t include things like database access, file access, and so forth in operator code. You want the performance of operators to be as fast as possible. Also, you want to make the operation intuitively logical as well. For example, if you have a plus operator, don’t make it subtract or divide! The bottom line is that another programmer shouldn’t have to look at your code to understand what is happening, they should be able to determine it intuitively. If they can’t, then an operator may not be the appropriate choice for that routine.
I hope you found this introduction to operator overloading informative and useful. Let me know what you think by leaving a comment or question, using the contact me button or just using the rating stars. That way I know if I’m covering is what you want to see, if it is helpful or not, or if you would like more information about a subject.
Entry Filed under: VB.NET Tutorials
Rate This Article:











3 Comments Add your own
1. Bennie | November 7th, 2007 at 1:17 am
use of raise to the power operator to do exponential calculations
iNumber = 10
iRsult = iNumber ^ 3
help
2. padmanaban | July 30th, 2008 at 8:35 am
Hi..
i Needed calculated two number by using in the operator overloading in the calculation of complex number calculated
3. confused | May 25th, 2009 at 2:44 am
Your example is confusing, not simple!
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed