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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube