Use Shared keyword in VB.NET

This article will discuss about shared keyword in VB.NET.
  • 4390

Shared keyword

A shared method is not accessed via an object instance like a regular method, but rather is accessed directly from the class. The shared keyword in VB.NET is the equivalent of the static keyword in C#. In VB.NET, the shared keyword can only be applied to methods within a class, however, in C#, the static keyword can be applied to both methods within a normal class, and also at the class level to make the entire class static.

Shared Variables

When we share a value across all instances of a class when every object of a given type should share the same variable. This is accomplished through the use of shared variables.

A shared variable is declared using the Shared keyword, much like a shared method:

Public Class hello
Private Shared roh As Integer
End Class

We have no need an instance of the class to call the method.

Such as

Public Class Rohatash
Public Shared Sub MyMethod()
// Do something in the method
End Sub
End Class

We can call shared method without create instance of class.

MyClass.MyMethod()

For Example

Module Module1

   Public NotInheritable Class Myclass

       Private Sub New()

       End Sub

 

       Public Shared Function Add(ByVal num1 As Integer,ByVal num2 As Integer) As Integer

           Return num1 + num2

       End Function

 

       Public Shared Function [Sub](ByVal num1 As Integer,ByVal num2 As Integer) As Integer

           Return num1 - num2

       End Function

       Public Shared Function Mul(ByVal num1 As Integer,ByVal num2 As Integer) As Integer

           Return num1 * num2

       End Function

   End Class

   Sub Main()

       Console.WriteLine("Sum= " & MyMath.Add(5, 2).ToString())

       Console.WriteLine("Substraction = " & MyMath.[Sub](9, 2).ToString())

       Dim mul As Integer = MyMath.Mul(7, 2)

       Console.WriteLine("Multiply  = " + mul)

   End Sub

End Module

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.