Home >>VB.Net Built-in Functions >VB.Net program to overload bitwise left shift (<<) operator

VB.Net program to overload bitwise left shift (<<) operator

Write a VB.Net program to overload bitwise left shift (<<) operator

Here, using the shared operator method, we can overload the left shift (<<) operator, which is used to perform a bitwise left shift operation on the class object.

Program :

Below is the source code for overloading the left shift (<<) operator. The program given is compiled and successfully executed.

'VB.net program to overload left shift "<<" operator.


Class Sample
    Dim num As Integer
    Sub SetValue(ByVal n As Integer)
        num = n
    End Sub

    Public Shared Operator <<(ByVal S1 As Sample, ByVal bits As Integer) As Integer
        Dim result As Integer = 0
        result = S1.num << bits
        Return result
    End Operator
End Class

Module Module1
    Sub Main()
        Dim obj As New Sample()
        Dim result As Integer = 0

        obj.SetValue(10)

        'left shift by 2 bits
        result = obj << 2

        Console.WriteLine("Result: {0}", result)
    End Sub
End Module
	
Output:
Result: 40
Explanation:

In the above program, we built a Sample class that includes two SetValue() methods and the operator method to overload the operator with the bitwise left shift (<<).

After that, we built a Module1 module that contains the Main() method, and the program entry point is the Main() method. And, we generated a Sample class object and used the SetValue() method to set the value of the data member and then execute the bitwise left shift operator on objects. The result is printed on the console screen after that.


No Sidebar ads