Home >>VB.Net Built-in Functions >VB.Net program to overload binary plus (+) operator

VB.Net program to overload binary plus (+) operator

Write a VB.Net program to overload binary plus (+) operator

Here, to apply binary plus operations between two objects, we can overload the binary plus (+) operator with a class.

Program :

Below is the source code for overloading the binary plus (+) operator. The program given is compiled and successfully executed.

'VB.net program to overload binary plus ("+") operator.

Class Sample
    Dim num1 As Integer
    Dim num2 As Integer
    Sub SetValues(ByVal n1 As Integer, ByVal n2 As Integer)
        num1 = n1
        num2 = n2
    End Sub
    Public Shared Operator +(ByVal S1 As Sample, ByVal S2 As Sample) As Sample
        Dim temp As New Sample()
        temp.num1 = S1.num1 + S2.num1
        temp.num2 = S1.num2 + S2.num2
        Return (temp)
    End Operator
    Sub PrintValues()
        Console.WriteLine(vbTab & "Num1: {0}", num1)
        Console.WriteLine(vbTab & "Num2: {0}", num2)
    End Sub
End Class
Module Module1
    Sub Main()
        Dim obj1 As New Sample()
        Dim obj2 As New Sample()
        Dim obj3 As New Sample()
        obj1.SetValues(10, 20)
        obj2.SetValues(30, 40)
        obj3 = obj1 + obj2
        Console.WriteLine("Obj1: ")
        Console.WriteLine("Obj2: ")
        Console.WriteLine("Obj3: ")
    End Sub
End Module
Obj1: Num1: 10 Num2: 20 Obj2:
Num1: 30 Num2: 40 Obj3:
Num1: 40 Num2: 60

We have created a Sample class in the above program, which includes two SetValues(), PrintValues() methods to set and print the values of the data members of the class. Here, one more method for overloading the binary plus (+) operator has been implemented.

After that, we built a Module1 module that contains the Main() method, and the program entry point is the Main() method. And, we created the two Sample Class objects and then performed the binary plus operation between the two objects, return the sum to be allocated to the third object.

No Sidebar ads