operator overloading in VB.NET ?

  • Thread starter Thread starter Chris
  • Start date Start date
Chris,
You need to try on VS.NET 2004 (Whidbey).

Also, you need to include that statement in the Point or Size
Class/Structure. As one of the arguments to the overloaded operator needs to
be of the class or structure the operator is in. In other words the XYZ
Module cannot define Overloaded Operators for the System.Drawing.Point or
System.Drawing.Size structures. Overloaded CType operators can have either
the return type or the parameter match the class they are in.

For example I could define a Complex Number, of course you would want to add
support for other conversions & operators.

' VS.NET 2004 (Whidbey - PDC) Syntax
Public Structure Complex

Private Readonly m_x As Double
Private Readonly m_y As Double

Public Sub New(ByVal x As Double, ByVal y As Double)
m_x = x
m_y = y
End Sub

Public Readonly Property X As Double
Get
Return m_x
End Get
End Property

Public Readonly Property Y As Double
Get
Return m_y
End Get
End Property

Public Shared Operator +(ByVal lhs As Complex, ByVal rhs As Complex)
As Complex
Return New Complex(lhs.m_x + rhs.m_x, lhs.m_y + rhs.m_y)
End Operator

Public Shared Widening Operator CType(ByVal x As Integer) As Complex
Return New Complex(x, 0)
End Operator

Public Overrides Function ToString()
Return String.Format("({0}, {1})", m_x, m_y)
End Function

End Structure

Then I can use it:

Dim c1, c2, c3 As Complex
c1 = 1
c2 = New Complex(1,2)
c3 = c1 + c2
Debug.WriteLine(c1, "c1")
Debug.WriteLine(c2, "c2")
Debug.WriteLine(c3, "c3")


Hope this helps
Jay
 
Back
Top