Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of a shared variable in VB.NET?

Tags:

vb.net

It is the same as static in C# and most other languages. It means that every object in the class uses the same copy of the variable, property or method. When used with a method as it is static you don't need an object instance.

MyClass.DoSomething()

rather than

Dim oObject as New MyClass()
oObject.DoSomething()

The "Shared" keyword in VB.NET is the equivalent of the "static" keyword in C#.

In VB.NET, the Shared keyword can be applied to Dim, Event, Function, Operator, Property, and Sub statements within a class; however, in C#, the static keyword can be applied both to these statements within a normal class, and also at the class level to make the entire class static.

A "Shared" or "static" method acts upon the "type" (that is, the class) rather than acting upon an instance of the type/class. Since Shared methods (or variables) act upon the type rather than an instance, there can only ever be one "copy" of the variable or method as opposed to many copies (one for each instance) in the case of non-shared (i.e., instance) methods or variables.

For example: If you have a class, let's call it MyClass with a single non-shared method called MyMethod.

Public Class MyClass
    Public Sub MyMethod()
        ' Do something in the method
    End Sub
End Class

In order to call that method you would need an instance of the class in order to call the method. Something like:

Dim myvar As MyClass = New MyClass()
myvar.MyMethod()

If this method was then made into a "shared" method (by adding the "Shared" qualifier on the method definition, you no longer need an instance of the class to call the method.

Public Class MyClass
    Public Shared Sub MyMethod()
        ' Do something in the method
    End Sub
End Class

And then:

MyClass.MyMethod()

You can also see examples of this in the .NET framework itself. For example, the "string" type has many static/shared methods. I.e.

' Using an instance method (i.e. Non-shared) of the string type/class.
Dim s As String = "hello"
s.Replace("h", "j")

' Using a static/shared method of the string type/class.
s = String.Concat(s, " there!");

Here's a good article that explains it further:

Shared Members and Instance Members in VB.NET


Simply whenever you want to have single instance of variable for entire application, shared between objects of your class. Instead of 1-per-object.