Home >>VB.Net Built-in Functions >VB.Net Program to overload unary minus (-) operator
To apply unary minus operation with data member of the class, we will overload the unary minus ('-') operator with a class here.
Program :Below is the source code for overloading the unary minus (-) operator. The program given is compiled and successfully executed.
'VB.net program to overload unary minus ("-") operator.
Class Sample
Dim num1 As Integer
Dim num2 As Integer
Sub SetValues(ByVal n1 As Integer, ByVal n2 As Integer)
num1 = n1
num2 = n2
End Sub
Public Shared Operator -(ByVal S As Sample) As Sample
Dim temp As New Sample()
temp.num1 = -S.num1
temp.num2 = -S.num2
Return (temp)
End Operator
Sub PrintValues()
Console.WriteLine("Num1: {0}", num1)
Console.WriteLine("Num2: {0}", num2)
End Sub
End Class
Module Module1
Sub Main()
Dim obj1 As New Sample()
Dim obj2 As New Sample()
obj1.SetValues(10, 20)
obj1.PrintValues()
obj2 = -obj1
obj2.PrintValues()
End Sub
End Module
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, one more way to overload the unary operator minus "-" was introduced.
After that, we built a Module1 module that contains the Main() method, and the program entry point is the Main() method. Here, the two objects of the Sample class is created and then the unary minus operation is done with object obj1 and assigned to obj2.