8

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?

Community
  • 1
  • 1
Flash
  • 15,945
  • 13
  • 70
  • 98
  • Same answers as the C++ question. All OOP design-patterns are going to be the similar, regardless of the language. There's nothing special here about VB.NET. – Cody Gray - on strike Apr 26 '11 at 14:09
  • 2
    @Cody But the accepted answer to that other question isn’t particularly good. – Konrad Rudolph Apr 26 '11 at 14:16
  • @Cody Fair enough - I thought the two compilers might treat them differently - and also couldn't get a straight answer out of the other question. – Flash Apr 26 '11 at 14:17
  • Old now, but @Cody: _Static in VB.Net is not at all the same thing as static in C++_. They are completely different concepts. VB.Net's analog to C++'s static is `Shared`. – Joel Coehoorn Sep 24 '13 at 20:00

2 Answers2

9

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
-1

I would NOT recommend this.

Static in Visual Basic means that one or more declared local variables are to continue to exist and retain their latest values after termination of the procedure in which they are declared. Reference: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/modifiers/static

So, why would you do that? Next time you come into this Sub you will anyways reinitialize this variable. I don't think you can even access it anymore, unless you would have a second instance of this class, and if both instances run at the same time the value of "a" could affect the value of the "a" in the second instance. Unless intended, that would be disastrous. As the previous answer stated correctly - the smaller the scope the better.

So, unless I am mistaken, this would be a very bad practice.

Leo Muller
  • 1,421
  • 1
  • 12
  • 20