Related C++ question: Static local variables in methods a bad practice?
In VB.NET, when I want a simple counter or something that increments each time a method is called, I often find myself writing code like:
Private Sub tmrRefresh_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrRefresh.Tick
Static a As Integer = 0
a += 1
'...rest of method depends on a
End Sub
Is this recommended in VB.NET and OOP in general?
Are static local variables bad practice?
No. Static local variables differ in exactly one regard to non-local private variables: they have a smaller scope. Since you always want to keep scope as small as possible (= better encapsulation), local statics can be advantageous over private variables.
On the flip-side, local static variables may be hard to initialise correctly. If a complex initialisation is required (for example, if you need to re-initialise a variable later on), local static variables may be unsuitable.