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

VB.Net Program to overload equal to (=) and not equal to (< >) operators

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

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

Program :

Below is the source code for overloads equal to (=) and not equal to (< >) operators. The program given is compiled and successfully executed.

'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
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 overload methods equal to (=) and not 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 Model 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 written on the console screen after that.