Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between Shared and Static?

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.

like image 304
sab669 Avatar asked Jun 19 '14 15:06

sab669


2 Answers

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

like image 199
Matt Wilko Avatar answered Sep 25 '22 20:09

Matt Wilko


For VB.Net you use shared exactly like Static is used in C#, but VB.Net has a static keyword as well and it is used to retain a variable value even after the method call has ended. So the next time you call a method it will have that previous value. MSDN has a more detailed explanation here - http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx

From the link there are some interesting behaviors:

When you declare a static variable in a Shared procedure, only one copy of the static variable is available for the whole application. You call a Shared procedure by using the class name, not a variable that points to an instance of the class.

When you declare a static variable in a procedure that isn't Shared, only one copy of the variable is available for each instance of the class. You call a non-shared procedure by using a variable that points to a specific instance of the class.

like image 35
Wade73 Avatar answered Sep 24 '22 20:09

Wade73