Home »
VB.Net »
VB.Net Programs
VB.Net program to overload equal to (=) and not equal to (<>) operators
By Nidhi Last Updated : November 15, 2024
Overloading equal to (=) and not equal to (<>) operators in VB.Net
Here, we will overload equal to (=) and not equal to (<>) 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 equal to (=) and not equal to (<>) operators is given below. The given program is compiled and executed successfully.
VB.Net code to overload equal to (=) and not equal to (<>) operators
'VB.net program to overload equal to (=) and
'not equal to (<>) 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(10)
If (obj1 = obj2) Then
Console.WriteLine("Obj1 is equal to Obj2")
Else
Console.WriteLine("Obj1 is not equal to Obj2")
End If
obj1.SetValues(30)
obj2.SetValues(20)
If (obj1 <> obj2) Then
Console.WriteLine("Obj1 is not equal to Obj2")
Else
Console.WriteLine("Obj1 is equal to Obj2")
End If
End Sub
End Module
Output:
Obj1 is equal to Obj2
Obj1 is not equal to 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 equal to (=) and not equal to (<>) 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. Here, 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 »