C# Static variables - scope and persistence

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

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.


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