Home >>VB.Net Built-in Functions >VB.Net Program to overload less than equal to (<=) and greater than equal to (>=) operators

VB.Net Program to overload less than equal to (<=) and greater than equal to (>=) operators

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

Here, using the shared operator method, which is used to perform comparisons on the object of the class, we will overload less than equal to (<=) and greater than equal to (>=).

Program :

Below is the source code that overloads less than equal to (<=) and greater than equal to (>=) the operator. The program given is compiled and successfully executed.


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(10)
        If (obj1 <= obj2) Then
            Console.WriteLine("Obj1 is less than equal to Obj2")
        Else
            Console.WriteLine("Obj1 is not less than qual to Obj2")
        End If
        obj1.SetValues(30)
        obj2.SetValues(20)
        If (obj1 >= obj2) Then
            Console.WriteLine("Obj1 is greater than equal to Obj2")
        Else
            Console.WriteLine("Obj1 is not greater than equal to Obj2")
        End If
    End Sub
End Module
	
Output:
Obj1 is less than equal to Obj2
Obj1 is greater than equal to 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 methods for overloading less than equal to the (<=) and greater than equal to the (>=) operator, so we can compare objects.

After that, we built a Module1 module that contains the Main() method, and the program entry point is the Main() method. Here, we created the two Main Class objects and used the SetValues() method to set the value of the data member and then perform object compare. The following message will be written on the console screen after that.


No Sidebar ads