Home »
VB.Net »
VB.Net Programs
VB.Net program to overload less than (<) and greater than (>) operator
By Nidhi Last Updated : November 15, 2024
Overloading less than (<) and greater than (>) operator in VB.Net
Here, we will overload less than (<) and greater than (>) operators using the shared operator method, which is used to perform comparations on the object of the class.
Program/Source Code:
The source code to overload less than (<) and greater than (>) operator is given below. The given program is compiled and executed successfully.
VB.Net code to overload less than (<) and greater than (>) operator
'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
Press any key to continue . . .
Explanation:
In the above program, we created a class Sample that contains two methods SetValues(), PrintValues() to set and print the values of data members of the class. Here, we also implemented methods to overload less than (<) and greater than (>) the operator, then we can perform comparation on objects.
After that, we created a module Module1 that contains the Main() method, the Main() method is the entry point for the program. And, we created the two objects of Sample class and set the value of data member using SetValues() method and then perform comparation on objects. After that appropriate message will be printed on the console screen.
VB.Net Basic Programs »