What are the differences between Shared and Static?

sab669 picture sab669 · Jun 19, 2014 · Viewed 17k times · Source

I'm a C# developer but I've inherited a legacy VB app today with 0 documentation what so ever. I've been starting to read through the code and reference the list of VB keywords every 5 seconds.

I guess I don't understand the distinction between Shared and Static.

Reading this post: https://stackoverflow.com/a/1980293/1189566

It states:

VB doesn't have static, it has shared

But you can see in the list of keywords linked above, Static is a reserved keyword. It looks like Static is only applicable to fields, where as Shared can be on a method or a field?

I guess ultimately I'm just hoping someone could expand upon the answer I linked to provide some more details for a VB noob.

For example, say I had this

public class MyClass
    Dim myVar as Integer = 1

    public shared sub UpdateMyVar()
        myVar = 2
    end sub
end class

public class MyOtherClass
    Dim cOne = New MyClass()
    Dim cTwo = New MyClass()

    cOne.UpdateMyVar()
    txtMyTextBox.Text = cTwo.myVar.ToString()
end class

Please forgive any syntactical issues. Assume this code compiles. I've literally just started skimming the code an hour and a half ago.

Would cTwo.myVar be 1 or 2? I'm guessing 2 since Shared seems to affect all instances of a class? That seems tremendously dangerous.

Answer

Matt Wilko picture Matt Wilko · Jun 19, 2014

The equivalent of the C# Static method modifier is Shared in VB.net

The closest equivalent of the C# Static class modifier in VB.Net is a Module

The Static keyword in VB.NET defines a local variable that exists for the lifetime of the process. There is no equivalent of this in C#.

For a great reference of comparison between the two see this link: https://www.harding.edu/fmccown/vbnet_csharp_comparison.html