VB.net Program to Overload Arithmetic Operators

You are currently viewing VB.net Program to Overload Arithmetic Operators

VB.Net program to overload arithmetic operators

'VB.net program to overload arithmetic operators.

Class Sample
    Dim num As Integer
    Sub SetValues(ByVal n As Integer)
        num = n
    End Sub

    Public Shared Operator +(ByVal S1 As Sample, ByVal S2 As Sample) As Sample
        Dim temp As New Sample()
        temp.num = S1.num + S2.num
        Return (temp)
    End Operator

    Public Shared Operator -(ByVal S1 As Sample, ByVal S2 As Sample) As Sample
        Dim temp As New Sample()
        temp.num = S1.num - S2.num
        Return (temp)
    End Operator

    Public Shared Operator *(ByVal S1 As Sample, ByVal S2 As Sample) As Sample
        Dim temp As New Sample()
        temp.num = S1.num * S2.num
        Return (temp)
    End Operator

    Public Shared Operator \(ByVal S1 As Sample, ByVal S2 As Sample) As Sample
        Dim temp As New Sample()
        temp.num = S1.num \ S2.num
        Return (temp)
    End Operator

    Public Shared Operator Mod(ByVal S1 As Sample, ByVal S2 As Sample) As Sample
        Dim temp As New Sample()
        temp.num = S1.num Mod S2.num
        Return (temp)
    End Operator

    Sub PrintValues()
        Console.WriteLine(vbTab & "Num: {0}", num)
    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(7)
        obj2.SetValues(2)

        Console.WriteLine("Obj1: ")
        obj1.PrintValues()

        Console.WriteLine("Obj2: ")
        obj2.PrintValues()

        obj3 = obj1 + obj2
        Console.WriteLine("Addition: ")
        obj3.PrintValues()

        obj3 = obj1 - obj2
        Console.WriteLine("Subtraction: ")
        obj3.PrintValues()

        obj3 = obj1 * obj2
        Console.WriteLine("Multiplication: ")
        obj3.PrintValues()

        obj3 = obj1 \ obj2
        Console.WriteLine("Division: ")
        obj3.PrintValues()

        obj3 = obj1 Mod obj2
        Console.WriteLine("Remainder: ")
        obj3.PrintValues()
    End Sub
End Module
Obj1:
        Num: 7
Obj2:
        Num: 2
Addition:
        Num: 9
Subtraction:
        Num: 5
Multiplication:
        Num: 14
Division:
        Num: 3
Remainder:
        Num: 1
Press any key to continue . . .

Ranjith Kumar

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply