1

I just realized that I can access shared members from instances of classes (probably this is not correct, but compile and run), and also learn/discover that, I can modify shared members, then create a new instance and access the new value of the shared member.

My question is, what happens to the shared members, when it comes back to the "default" value (class declaration), how dangerous is it do this ? is it totally bad ? is it valid in some cases ?.

If you want to test my point here is the code (console project vb.net) that I used to test shared members, as you can see/compile/run, the shared member "x" of the class "Hello" has default value string "Default", but at runtime it changes it, and after creating a new object of that class, this object has the new value of the shared member.

Module Module1
    Public Class hello

        Public Shared x As String = "Default"

        Public Sub New()

        End Sub
    End Class

    Sub Main()

         Console.WriteLine("hello.x=" & hello.x)
         Dim obj As New hello()

         Console.WriteLine("obj.x=" & obj.x)
         obj.x = "Default shared memeber, modified in object"
         Console.WriteLine("obj.x=" & obj.x)

         hello.x = "Defaul shared member, modified in class"
         Console.WriteLine("hello.x=" & hello.x)

         Dim obj2 As New hello()
         Console.WriteLine("obj2.x=" & obj2.x)

          Console.ReadLine()

     End Sub

End Module

UPDATE: First at all, thanks to everyone, each answer give feedback, I suppose, by respect I should choose one as "the answer", I don't want to be offensive to anyone, so please don't take it so bad if I didn't choose you answer.

1
  • This isn't really an 'answer', so leaving it as a comment. Normally, I only use shared or static variables/methods in a class that ONLY contains shared/static content. What's more, I normally create a private constructor for that class just to make it clear that it can't be instantiated (singleton). Not saying that's gospel - just how I normally deal with it to keep confusion at bay.
    – Ducain
    Commented Mar 2, 2012 at 20:58

4 Answers 4

3

Shared (or static) members don't have an instance. They are not 'part' of an object. Think of shared members or functions as communal. If one piece of code updates a shared member, the next piece of code to access it will see the new value. Shared means 'shared memory'. It's important to understand whose memory it is. Shared memory is shared by all threads within the process space. So, you might be even more surprised if you spun up another thread and tried to access the shared memory space. Your child thread will update the memory of the main thread.

In some languages (e.g., C), you don't need to associate everything with a containing class or module. In other languages (e.g., VB) you provide a context for your member in the form of a class, but that's really only so you can a) find it, and b) hide it if you want to.

Private shared members will be visible only to members of a class, but they're still shared. With shared functions, each caller gets a copy of any parameters passed to the function, but that's it. If the function uses any shared members, they are potential trouble spots for two reasons. First, later on in your code, you might forget who/what last updated the shared member so it could have an unexpected value. Second, if your program is multithreaded, you can create resource contention which are very difficult to diagnose.

Shared members and functions are absolutely valid in many cases. You should consider what you're trying to do, whether there might be write-contention for a given resource, and whether there are performance considerations (e.g., caching). If you're a beginner programmer, I'd suggest you fully understand shared members/functions before you get into the habit of using them. A good place to use them is with functions that don't have side-effects (i.e., that don't change program state by setting other members). Then you might use them for things like caches (if you really need that) among other things. Just don't abuse them.

2

In general I recommend against the use of shared/static variables. Wherever possible use instance variables. There are rare exceptions in my view.

One of the cases where a shared/static variable may make sense is when you want to introduce constants, although some language support constants as a separate concepts. In VB.NET and C# (and possibly other .NET languages) please be aware that there is a difference between a constant and a read-only variable (declared as 'ReadOnly' in VB.NET or 'readonly' in C#).

A shared/static variable is in some sense a 'global' variable, although you can restrict access to it by using appropriate access modifiers. Global variables are considered to be bad practice and can be extremely difficult to debug, e.g. when there are a gazillion places where your code writes to or reads from that variable, and in particular if the content of the shared/static variable influences the logic of your code, e.g. when used in an if-statement.

From an object-oriented perspective you could argue that a shared/static variable is breaking encapsulation.

There are many other aspects and factors that you may need to consider. In general I advise my teams against them although there are reasonable exceptions where they make sense. In summary:

  • Yes, shared/static variable are dangerous
  • No, they are not bad as such
  • Yes, their use is a valid and appropriate approach in select cases
1

what happens to the shared members, when it comes back to the "default" value (class declaration), how dangerous is it do this ?

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

It is more typical to declare a non-static class with some static members, than to declare an entire class as static.

Two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Quoted from MSDN-Static Classes and Static Class Members.

is it totally bad ? is it valid in some cases ?.

No it is not bad, just be careful and use it when it is appropriate. It all depends on what you want to do.

5
  • At least in vb.net, I can access to shared members from instances not only from the class itself, I mean I can have an instance and use it to access to the shared/static member, how bad/wrong is this ? I mean, I'm kind of surprised/confused, because the .net let me access to shared members from instance besides the class, My idea of shared member was, that I couldn't access (much less modify the shared member from an instance), how "normal" is this behavior or is it a thing of VB.net ? and if I set a new value from an instance, when the shared member's class recovers its original value ?
    – Allende
    Commented Mar 2, 2012 at 20:16
  • if the member is static, you can access it without creating a object. This is a feature. Let's say you want all the objects to have the same value of a property called CompanyName and say, you have 100 objects. You can set the CompanyName to 'GM' in one line instead of making 100 assignments. If you don't want to use this feature, simply don't declare your members as static in non-static (shared) classes.
    – NoChance
    Commented Mar 2, 2012 at 20:20
  • So, in short, is perfectly valid in a Oriented-Object language have static members, and access to them through the class or the instance (for example as you say to increment a counter of instances). ?
    – Allende
    Commented Mar 2, 2012 at 20:26
  • In Object Oriented Programing, the mostly used approach is to declare members as non-static (non-shared) and access them after you have established an object from the class. However, the languages are flexible enough, to allow you to do it differently as explained before.
    – NoChance
    Commented Mar 2, 2012 at 20:29
  • @Allende, did this answer help you?
    – NoChance
    Commented Mar 3, 2012 at 21:40
1

In several programming languages with classes that support "static members", each single class is managed internally as if it were a namespace, and its "static members" as global variables. This happens without the class being instantiated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.