How to write a user-defined operator in VB.NET

1 Answer

0 votes
Imports System

Public Class Point
    Public Property X As Integer
    Public Property Y As Integer

    Public Sub New(x As Integer, y As Integer)
        Me.X = x
        Me.Y = y
    End Sub

    ' Overloading the + operator (user-defined operator)
    Public Shared Operator +(p1 As Point, p2 As Point) As Point
        Return New Point(p1.X + p2.X, p1.Y + p2.Y)
    End Operator

    Public Overrides Function ToString() As String
        Return $"({X}, {Y})"
    End Function
End Class

Module Program
    Sub Main()
        Dim p1 As New Point(5, 8)
        Dim p2 As New Point(1, 2)

        Dim result As Point = p1 + p2 ' Using the overloaded + operator
        Console.WriteLine(result)
    End Sub
End Module

 
 

' run:
' 
' (6, 10)
'

 



answered Aug 3, 2025 by avibootz
...