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!");
No comments:
Post a Comment