About shared (static) Members and its behavior
Posted
by
Allende
on Programmers
See other posts from Programmers
or by Allende
Published on 2012-03-02T19:13:58Z
Indexed on
2012/12/20
11:13 UTC
Read the original article
Hit count: 294
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.
© Programmers or respective owner