This post originated from an RSS feed registered with .NET Buzz
by Raymond Lewallen.
Original Post: Operator Overloading in VB.Net 2.0
Feed Title: Raymond Lewallen
Feed URL: /error.htm?aspxerrorpath=/blogs/raymond.lewallen/rss.aspx
Feed Description: Patterns and Practices, OOP, .Net and Sql
The .Net framework version 2.0 brings many new things to developers
in all languages. This has been talked about quite a bit, but I just
wanted to refresh everybody on one of things I know I'm looking forward
to. Operator overloading. If you've done any programming in C#,
none of this is new to you. If you are strictly VB.Net, or new to
any .Net language, then read on.
Operator overloading is the act of making something happen when
somebody wants to use an operator, such as + (plus sign) to add two or
more objects together. At present, you can't do this in VB.Net in fx
1.0, 1.1. Let's look at how we accomplish adding objects together in
current release versions of VB.Net
The VB.Net 1.1 way
PublicClass RoadTrip
PublicSubNew()
EndSub
PublicSubNew(ByVal milesTraveled As Int32)
CheckValue(milesTraveled)
_miles = milesTraveled
EndSub
PrivateSub CheckValue(ByVal value As Int32)
If value < 0 ThenThrowNew ArgumentOutOfRangeException("Value")
EndSub
Private _miles As Int32
PublicProperty Miles() As Int32
Get
Return _miles
EndGet
Set(ByVal Value As Int32)
CheckValue(Value)
_miles = Value
EndSet
EndProperty
PublicSharedFunction Add(ByVal roadTripOne As RoadTrip, ByVal roadTripTwo As RoadTrip) As RoadTrip
Nothing wrong with that. Just pop in an add function and we
get the functionality that we want. Consider a slight
drawback. The API user has to know there is an Add method, which
intellisense pretty much provides to the user, so its really not even a
drawback. Letâs implement the above code:
Implementing the above 1.1 code
PublicSub ShowExample()
Dim roadTripOne AsNew RoadTrip(100)
Dim roadTripTwo AsNew RoadTrip(250)
Console.WriteLine("Road trip one was {0} miles.", roadTripOne.Miles)
Console.WriteLine("Road trip two was {0} miles.", roadTripTwo.Miles)
Console.WriteLine("Total trip was {0} miles.", totalTrip.Miles)
EndSub
The output
Road trip one was 100 miles.
Road trip two was 250 miles.
Total trip was 350 miles.
What operator overloading allows us to do is not have the Add
method, but include an operator that performs the same actions.
In this case, it will be + (plus sign)
The VB.Net 2.0 way
PublicClass RoadTrip
PublicSubNew()
EndSub
PublicSubNew(ByVal milesTraveled As Int32)
CheckValue(milesTraveled)
_miles = milesTraveled
EndSub
PrivateSub CheckValue(ByVal value As Int32)
If value < 0 ThenThrowNew ArgumentOutOfRangeException("Value")
EndSub
Private _miles As Int32
PublicProperty Miles() As Int32
Get
Return _miles
EndGet
Set(ByVal Value As Int32)
CheckValue(Value)
_miles = Value
EndSet
EndProperty
PublicSharedOperator +(ByVal roadTripOne As RoadTrip, ByVal roadTripTwo As RoadTrip) As RoadTrip