Code Focused

Local Static Variables in Visual Basic and C#

Here's another area where the two languages differ.

The original C language was a great programming tool. Created back in the early 1970s, it remains one of the most influential computer languages more than four decades later. As a .NET developer, you know that the obvious grammatical descendant of the C language is Visual Basic. At least, that's the case if you're talking about local static variables.

In C, static variables appear within local procedures, just like other local variables, but they have lifetimes that span the entire runtime of the application. In terms of value access, they're a lot like global variables, yet scoped to just a single routine:

/* ----- C language example */
void DoSomeWork()
{
  /* ----- Initialization the first time through. */
  static int visitsToThisRoutine = 0;

  /* ----- Keep track of visits. */
  ++visitsToThisRoutine;
  /* ----- Then do whatever else needs doing. */
}

Anytime you return to the routine, you'll find the static variable still in possession of whatever data value you left it with the last time you visited.

In Visual Basic, local static variables, likewise, exhibit a lifespan that surpasses their containing routines:

' ----- Visual Basic example
Sub DoSomeWork()
  ' ----- Initialization the first time through.
  Static visitsToThisRoutine As Integer = 0

  ' ----- Keep track of visits.
  visitsToThisRoutine += 1
  ' ----- Then do whatever else needs doing.
End Sub

The actual lifetime depends on the specific type that contains the routine. Within Shared types or modules, or inside Shared methods, static variables survive for the entire application's run, just like in C. For non-Shared types, such variables live as long as a specific instance lives. The big surprise here isn't that there are different lifetimes for different situations. The surprise is that C# doesn't support local static variables at all.

Why this is, who can say? Perhaps it's the result of teenage rebellion from a language that swore it would never be like its parent language. Whatever the cause, the good news is that you can easily emulate this Visual Basic feature in C# with a simple type-level helper field or property:

// ----- Initialization before the first use.
private int VisitsToWorkRoutine = 0;
void DoSomeWork()
{
  // ----- Keep track of visits.
  ++this.VisitsToWorkRoutine;
  // ----- Then do whatever else needs doing.
}

This is all well and good for the core value types. But one nice thing about C static variables was that if you didn't access the routine that contained them, they were never initialized. For variables that allocate significant resources during initialization -- a major reason for using static variables in the first place--letting such initialization occur at class instantiation might be a poor choice. A quick workaround is to initialize the variable to a null state, and then only allocate the resource when needed:

private System.Text.StringBuilder Content = null;
void DoSomeWork()
{
  // ----- Initialize the first time through.
  if (this.Content == null)
    this.Content = new System.Text.StringBuilder(100000);
  // ----- Then do whatever else needs doing.
}

By postponing initialization until the routine runs, C# doesn't waste time initializing resources that might never get used. Although this is better, it's still not a perfect replacement for actual static variables. One concern is that other methods within the class can access the pseudo-static field with abandon. But in a C# world devoid of true static variables, it's good to know that the language can be somewhat like its parent.

About the Author

Tim Patrick has spent more than thirty years as a software architect and developer. His two most recent books on .NET development -- Start-to-Finish Visual C# 2015, and Start-to-Finish Visual Basic 2015 -- are available from http://owanipress.com. He blogs regularly at http://wellreadman.com.

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events