ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

VB.Net program to overload unary minus (-) operator

Here, we are going to learn how to overload unary minus (-) operator in VB.Net?
Submitted by Nidhi, on December 30, 2020

Here, we will overload the unary minus ('-') operator with a class to apply unary minus operation with data member of the class.

Program/Source Code:

The source code to overload unary minus (-) operator is given below. The given program is compiled and executed successfully.

'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

Output:

Num1: 10
Num2: 20
Num1: -10
Num2: -20
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 implemented one more method to overload the unary minus "-" operator.

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 the Sample class and then perform the unary minus operation with object obj1 and assigned them to the obj2.

VB.Net Basic Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.