• 12737

When an operator can perform more than one operations, specially with objects, known as operator overloading.A function name can be replaced with the operator using operator keyword.

• Don't change an operator's semantic meaning. The result of an operator should be intuitive.
• Make certain overloaded operators are shared methods.
• You cannot overload assignment e.g., the "=" operator .

VB.NET allows the following operators to be overloaded:

• + (increment/plus - unary and binary)>
• - (decrement/minus - unary and binary)
• Not (unary)
• * (multiply - binary)
• / (divide - binary)
• \ (integer divide - binary)
• & (concatenate - binary)
• Like (binary)
• Mod (binary)
• And (binary)
• Or (binary)
• ^ (raise to power - binary)
• << (left shift - binary)
• >> (right shift - binary)
• = (equals - binary)
• <> (not equals - binary)
• < (less than - binary)
• > (greater than - binary)
• <= (less than or equal to - binary)
• >= (greater than or equal to - binary)

Module module1

Class Size

Private feet As Integer, inch As Integer

Public Sub New(ByVal f As Integer, ByVal i As Integer)

feet = f

inch = i

End Sub

Public Sub ShowSize()

Console.WriteLine("Size is {0} feet and {1} inch", feet, inch)

End Sub

Public Shared Function Add(ByVal x As Size, ByVal y As Size) As Size       'add method

Dim f As Integer = x.feet + y.feet

Dim i As Integer = x.inch + y.inch

If i >= 12 Then

i = i - 12

f += 1

End If

Return New Size(f, i)

End Function

Public Shared Operator +(ByVal x As Size, ByVal y As Size) As Size             ' add method replace with operator(+) using operator keyword

Dim f As Integer = x.feet + y.feet

Dim i As Integer = x.inch + y.inch

If i >= 12 Then

i = i - 12

f += 1

End If

Return New Size(f, i)

End Operator

Public Shared Sub Main()

Dim s1 As New Size(5, 9)

Dim s2 As New Size(8, 8)

'Dim s3 As Size = s1 +s2                           ' + operator perform the task

s3.ShowSize()

End Sub

End Class

End Module

OUTPUT : In the above example (+) operator perform more than one operation. the function name add replace with the operator using Operator keyword.