Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Static variables - scope and persistence

I just did a little experiment:

public abstract class MyClass
{
  private static int myInt = 0;

  public static int Foo()
  {
    return myInt;
  }

  public static int Foo(int n)
  {
    myInt = n;
    return bar();
  }

  private static int bar()
  {
    return myInt;
  }
}

and then I ran:

MessageBox.Show(MyClass.Foo().ToString());
MessageBox.Show(MyClass.Foo(3).ToString());
MessageBox.Show(MyClass.Foo().ToString());
MessageBox.Show(MyClass.Foo(10).ToString());
MessageBox.Show(MyClass.Foo().ToString());

The results I expected were 0, 3, 0, 10, 0.

To my surprise, I got 0, 3, 3, 10, 10.

How long do these changes persist for? The duration of the program execution? The duration of the function calling the static method?

like image 790
Ozzah Avatar asked May 13 '11 00:05

Ozzah


4 Answers

They will persist for the duration of AppDomain. Changes done to static variable are visible across methods.

MSDN:

If a local variable is declared with the Static keyword, its lifetime is longer than the execution time of the procedure in which it is declared. If the procedure is inside a module, the static variable survives as long as your application continues running.

See following for more details:

  • C#6 Language Specification - Static Variables
  • C#6 Language Specification - Application Startup
  • MSDN: Static Variable
  • MSDN: Variable Lifetime
like image 96
YetAnotherUser Avatar answered Sep 22 '22 23:09

YetAnotherUser


The results I expected were 0, 3, 0, 10, 0.

To my surprise, I got 0, 3, 3, 10, 10.

I'm not sure why you would expect the static variable to revert back to its original value after being changed from within the Foo(int) method. A static variable will persist its value throughout the lifetime of the process and only one will exist per class, not instance.

like image 22
Ed S. Avatar answered Sep 23 '22 23:09

Ed S.


If it's a static variable, that means it exists exactly one place in memory for the duration of the program.

like image 9
Chris Eberle Avatar answered Sep 20 '22 23:09

Chris Eberle


Per the C# spec, a static variable will be initialized no later than the first time a class is loaded into an AppDomain, and will exist until that AppDomain is unloaded - usually when the program terminates.

like image 5
Ben Avatar answered Sep 21 '22 23:09

Ben