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

  • AI for GitHub Collaboration? Maybe Not So Much

    No doubt GitHub Copilot has been a boon for developers, but AI might not be the best tool for collaboration, according to developers weighing in on a recent social media post from the GitHub team.

  • Visual Studio 2022 Getting VS Code 'Command Palette' Equivalent

    As any Visual Studio Code user knows, the editor's command palette is a powerful tool for getting things done quickly, without having to navigate through menus and dialogs. Now, we learn how an equivalent is coming for Microsoft's flagship Visual Studio IDE, invoked by the same familiar Ctrl+Shift+P keyboard shortcut.

  • .NET 9 Preview 3: 'I've Been Waiting 9 Years for This API!'

    Microsoft's third preview of .NET 9 sees a lot of minor tweaks and fixes with no earth-shaking new functionality, but little things can be important to individual developers.

  • Data Anomaly Detection Using a Neural Autoencoder with C#

    Dr. James McCaffrey of Microsoft Research tackles the process of examining a set of source data to find data items that are different in some way from the majority of the source items.

  • What's New for Python, Java in Visual Studio Code

    Microsoft announced March 2024 updates to its Python and Java extensions for Visual Studio Code, the open source-based, cross-platform code editor that has repeatedly been named the No. 1 tool in major development surveys.

Subscribe on YouTube