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

  • Microsoft Revamps Fledgling AutoGen Framework for Agentic AI

    Only at v0.4, Microsoft's AutoGen framework for agentic AI -- the hottest new trend in AI development -- has already undergone a complete revamp, going to an asynchronous, event-driven architecture.

  • IDE Irony: Coding Errors Cause 'Critical' Vulnerability in Visual Studio

    In a larger-than-normal Patch Tuesday, Microsoft warned of a "critical" vulnerability in Visual Studio that should be fixed immediately if automatic patching isn't enabled, ironically caused by coding errors.

  • Building Blazor Applications

    A trio of Blazor experts will conduct a full-day workshop for devs to learn everything about the tech a a March developer conference in Las Vegas keynoted by Microsoft execs and featuring many Microsoft devs.

  • Gradient Boosting Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the gradient boosting regression technique, where the goal is to predict a single numeric value. Compared to existing library implementations of gradient boosting regression, a from-scratch implementation allows much easier customization and integration with other .NET systems.

  • Microsoft Execs to Tackle AI and Cloud in Dev Conference Keynotes

    AI unsurprisingly is all over keynotes that Microsoft execs will helm to kick off the Visual Studio Live! developer conference in Las Vegas, March 10-14, which the company described as "a must-attend event."

Subscribe on YouTube