tags:

views:

3256

answers:

3

What is the use of shared variable in vb.net?

+3  A: 

Same as static in C# and most other languages. It means that every object in the class uses the same copy of the variablle, 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()
MrTelly
The asker specificaly asked about shared variables, not shared methods.
Binary Worrier
Mentally replace DoSomething() with Something to make the post apply to variables instead of methods.
OregonGhost
+1  A: 

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

Bartek Szabat
A: 

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.

A "shared" or "static" method acts upon the "type" (i.e. 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. ie.

// 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

CraigTP
The approximate equivalent of a static (Shared) class in VB is a Module.
Antony Highsky