Operator Overloading in VB.NET Whidbey
So, I'm going through all of the new features of VB.NET Whdibey and posting my findings and samples. The next topic I tackled was operators. The first time I saw this I got it, so it was easy to implement. I never knew how much I needed this feature! Consider the following class:
Public
Class OrderItem
Private _productid As String
Private _quantity As Int32
Private _unitprice As Decimal
Public Property ProductID() As String
Get
Return _productid
End Get
Set(ByVal Value As String)
_productid = Value
End Set
End Property
Public Property Quantity() As Int32
Get
Return _quantity
End Get
Set(ByVal Value As Int32)
_quantity = Value
End Set
End Property
Public Property UnitPrice() As Decimal
Get
Return _unitprice
End Get
Set(ByVal Value As Decimal)
_unitprice = Value
End Set
End Property
Public ReadOnly Property Total() As Decimal
Get
Return UnitPrice * Quantity
End Get
End Property
Public Shared Operator +(ByVal Item1 As OrderItem, ByVal Item2 As OrderItem) As OrderItem
If Item1.ProductID <> Item2.ProductID Then
Throw New Exception("You can only add OrderItems where the ProductID is the same for both objects")
ElseIf Item1.UnitPrice <> Item2.UnitPrice Then
Throw New Exception("You can only add OrderItems where the UnitPrice is the same for both objects")
Else
Dim item As New OrderItem
With item
.ProductID = Item1.ProductID
.Quantity = Item1.Quantity + Item2.Quantity
.UnitPrice = Item1.UnitPrice
End With
Return item
End If
End Operator
End
Class
It's all pretty straight-ahead until you get to the Operator. Public Shared Operator + is the meat of it. That's saying “I want this code to execute when someone adds two of my objects together with the + operator. The arguments represent the addends (is that the right word?) and the result is what's returned on the left of the equal sign.
My operator basically insures that the productid and unit price are the same for both objects, and then simply adds the quantities together.
Here is some code in a button to test it.
Dim Item1 As New OrderItem
Dim Item2 As New OrderItem
Dim Item3 As OrderItem
With Item1
.ProductID = "1"
.Quantity = 5
.UnitPrice = 10
End With
With Item2
.ProductID = "1"
.Quantity = 4
.UnitPrice = 10
End With
Item3 = Item1 + Item2
'-- This shows 90!
MsgBox(Item3.Total)