Home >>VB.Net Built-in Functions >Write a VB.Net Program to overload less than (<) and greater than (>) operator

Write a VB.Net Program to overload less than (<) and greater than (>) operator

Write a VB.Net Program to overload less than (<) and greater than (>) operator

Here, less than (<) and greater than (>) operators will be overload using the shared operator method that is used to make class object comparisons.

Program :

Below is the source code for an overload of less than (<) and greater than (>) operator. The program given is compiled and successfully executed.

'VB.net program to overload less than (<)

'and greater than (>) operator.


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 Boolean
        If (S1.num < S2.num) Then
            Return True
        Else
            Return False
        End If
    End Operator
    Public Shared Operator >(ByVal S1 As Sample, ByVal S2 As Sample) As Boolean
        If (S1.num > S2.num) Then
            Return True
        Else
            Return False
        End If
    End Operator
    Sub PrintValues()
        Console.WriteLine("Num: {0}", num)
    End Sub
End Class
Module Module1
    Sub Main()
        Dim obj1 As New Sample()
        Dim obj2 As New Sample()
        obj1.SetValues(10)
        obj2.SetValues(20)
        If (obj1 < obj2) Then
            Console.WriteLine("Obj1 is less than Obj2")
        Else
            Console.WriteLine("Obj2 is less than Obj1")
        End If
        obj1.SetValues(30)
        obj2.SetValues(20)
        If (obj1 > obj2) Then
            Console.WriteLine("Obj1 is greater than Obj2")
        Else
            Console.WriteLine("Obj2 is greater than Obj1")
        End If
    End Sub
End Module
	
Output:
Obj1 is less than Obj2
Obj1 is greater than Obj2
Explanation:

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, we have also added ways to overload less than (<) and greater than (>) the operator, so we can perform object comparisons.

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 Main Class objects and used the SetValues() method to set the value of the data member and then perform object comparison. The following message will be printed on the console screen after that.


No Sidebar ads