Dayan
Dayan

Reputation: 8031

Static keyword proper usage?

Regarding the static keyword.

Up to this point, via my own research, I have a general idea of what the static keyword is, but I feel that all these different descriptions and details have only confused me more. At the moment, I really don't feel that I know how to properly use "static"; it seems to be used differently between C# and VB.NET and applies differently within the language depending on what you are using it for…

While reading the MSDN article Static (Visual Basic) , many questions arose, specifically when I read this sentence:

Normally, a local variable in a procedure ceases to exist as soon as the procedure terminates. A static variable remains in existence and retains its most recent value.

  1. Is the VB.NET version of static the same as C# or Java, is the concept the same for most languages?

  2. If static retain a value within a class, and we are able to access that certain member, function without instantiating the class, is this safe to use loosely? In other words, should we keep a close eye when using static’s within classes? They remind me of global variables for some reason. Maybe I’m just being ignorant here and simply need more practice to understand their purpose.

  3. What are good scenarios where using static benefits and promotes reusability of code?

Upvotes: 8

Views: 3145

Answers (3)

Tim Copenhaver
Tim Copenhaver

Reputation: 3302

  1. VB.NET's shared is the same as C#'s static. C#'s static is pretty much the same as static in Java and most other languages. The concepts carry over.
  2. This is a yes and no kind of question. You don't want to just randomly throw statics around without knowing what you're doing. However, they can be useful for a lot of situations (more on that in #3). They are not really like global variables because they are still "namespaced" and organized by the class they belong to.
  3. Static members are typically used for utility methods and classes. For example, C# implements most of the Math library as static methods, since they're just doing computations and have no other side effects. As a general rule, if your method has no side effects, and all of the data it needs to do its job comes in as parameters. You can also use static properties if you want to share some data between instances of a class (for example, to track how many times a given method has been called, or something similar). Static also has some memory usage benefits, since it allows you to create only one instance of a class or method to share throughout the application, rather than creating new copies for each usage. You also use static classes for extension methods, but that's a whole other discussion.
  4. You didn't ask specifically, but it's worth mentioning the downsides. The biggest reason to avoid static is maintainability. You cannot inherit or extend static classes easily, which is a major thing to think about. So long as you stick to the composition over inheritance rule, this isn't necessarily a deal-breaker, but the lack of inheritance and polymorphism for static classes is a major drawback. That one issue by itself leads a lot of people to suggest avoiding static in all cases.

Upvotes: 5

asawyer
asawyer

Reputation: 17808

In C# the static keyword is the same as the shared keyword in VB.NET. Namely, from Static Classes and Static Class Members (C# Programming Guide):

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class.

In VB.NET static works very differently, as it applies to variables, not types.

I do not know if there is a C# equivalent for this behavior.

1) Is the VB.NET version of static the same as C# or Java, and is the concept the same for most languages?

It's different. shared is the same, though.

2) If static retain value within a class, and we are able to access that certain member, function without instantiating the class – Is this safe to use loosely? In other words, should we keep a close eye when using static’s within classes? They remind me of global variables for some reason, maybe I’m just being ignorant here and simply need more practice to understand their purpose.

Be very careful, they are global to the application domain.

3) What are good scenarios where using static benefits and promotes reusability of code?

I use static lists to cache sets of data that are used to populate dropdown lists so that I don't have to keep hitting SQL Server as one example.

Upvotes: 9

Gideon Engelberth
Gideon Engelberth

Reputation: 6155

The other answers dealt with the C# usages of static, so I'll talk about Static in VB.NET since you referenced an MSDN article about it. When you make a Static local variable in VB.NET, the compiler will translate that to a class-level variable that can only be referenced by code in the function in which the variable is declared in code. Whether said variable is instance or shared depends on the containing function. For example, this code:

Public Class StaticTest

    Public Function Process(value As Integer) As Integer
        Static lastValue As Integer
        Dim result As Integer
        If value > 0 Then
            result = value
            lastValue = value
        Else
            result = lastValue
        End If
        Return result
    End Function

End Class

Decompiles to something like this:

Public Class StaticTest
    ' Methods
    <DebuggerNonUserCode> _
    Public Sub New()
    End Sub

    Public Function Process(ByVal value As Integer) As Integer
        If (value > 0) Then
            Dim result As Integer = value
            Me.$STATIC$Process$20188$lastValue = value
            Return result
        End If
       Return Me.$STATIC$Process$20188$lastValue
    End Function

    ' Fields
    Private $STATIC$Process$20188$lastValue As Integer
End Class

I noticed that if I set lastValue to value on entrance into the function, the compiler also created some sort of initialization code and extra fields, so there are some cases where Static locals do generate some extra code.

I would recommend avoiding using Static locals because I find them more confusing then helpful when compared to the alternative, actually declaring a class-level instance variable. The tradeoffs of Statics are:

For:

  • Cannot be accessed in another function

Against:

  • Cannot be initialized in constructor (but can be initialized inline with their declaration, which gives the extra init field/code I mentioned above)
  • Cannot be located according to your typcial placement of class locals in code
  • Look like locals but are not

Upvotes: 6

Related Questions