Polymorphism and Operator Overloading don't mix !
Posted
Friday, January 07, 2005 12:51 PM
by
bill
Just like drinking and driving, seperately both are fun things, but put them together and we have a situation where loss becomes a likely result 
Consider this code :
Public Class Invoice
Public Price As Decimal
Shared Operator +(ByVal first As Invoice, ByVal second As Invoice) As Invoice
Dim retVal As New Invoice
retVal.Price = first.Price + second.Price
Return retVal
End Operator
Public Overrides Function ToString() As String
Return "Invoice Price = " & Me.Price
End Function
End Class
Public Class ShippingInvoice
Inherits Invoice
Public ShiipingCost As Decimal
Shared Shadows Operator +(ByVal first As ShippingInvoice, ByVal second As ShippingInvoice) As ShippingInvoice
Dim retVal As New ShippingInvoice
With retVal
.Price = first.Price + second.Price
.ShiipingCost = first.ShiipingCost + second.ShiipingCost
End With
Return retVal
End Operator
Public Overrides Function ToString() As String
Return "ShippingInvoice Price = " & Me.Price & ", ShippingCost = " & Me.ShiipingCost
End Function
End Class
Now if you then had a method such as :
Sub PolyAndOpsDontMix(ByVal a As Invoice, ByVal b As Invoice)
Console.WriteLine((a + b).ToString)
End Sub
And you call that, passing into the mehtod ShippingInvoices, the console output will be of type Invoice, not ShippingInvoice, and hence all the ShippingCost information is lost. The operator is based on the type of the operands at compile time, not runtime. So be careful when using Operator Overlaoding, especially when the operands are passed into a method, and hence polymorphism should apply. If in doubt seal those classes (NotInheritable) or use a method call, rather than an operator. Remeber operator overlaoding can be fun, and so too can polymorphism, but mixing the two can result in data loss. 