Frans Bouma said:
Now I'm interested in what these situations are. Could you give an
explanation where it will give much BETTER code than when you wouldn't
have the Static keyword?
I never said that it will give /much/ better code! One of the Windows Forms
FAQs is how to execute certain code only the first time a Windows Forms form
is activated. There are many different solutions to the problem which have
different advantages and disadvantages. Sure, you could create a private
field instead of the static variable below, but I think that a static
variable encapsulates the whole functionality more tightly:
\\\
Private Sub Form1_Activated( _
ByVal sender As Object, _
ByVal e As EventArgs _
) Handles MyBase.Activated
Static IsActivated As Boolean
If Not IsActivated Then
IsActivated = True
Application.DoEvents() ' ...
MsgBox("Form activated for the first time!")
End If
End Sub
///
Today's code often suffers from the problem that private variables holding
values used in a method or property semantically belong to a certain method
or property, and /not/ to the whole class. For methods this problem can be
reduced by using static variables. Similar functionality for properties
would be great, for example, something like the code below:
\\\
Public Property TheFoo() As Foo
Dim TheFooValue As Foo
Get
Return TheFooValue
End Get
Set(ByVal Value As Foo)
TheFooValue = Value
End Set
End Property
///
However, this is currently not supported.