C# Static variables - scope and persistence

吃可爱长大的小学妹 提交于 2019-11-26 18:54:51
YetAnotherUser

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:

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.

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.

For the duration of the program execution.

Static class variables are like globals. They're not connected to specific objects of a class - there's only one instance of those per program. The only variables that live during function execution time are automatic (local) variables of the function.

It persist for duration of the program execution, or until you overwrite it with another value. If you want to make the result as what you want it to be, you should specify myInt = 0 in the constructor before return myInt;

They persist "for the lifetime of the application domain in which your program resides" according to Microsoft Docs: Static Classes and Static Class Members (C# Programming Guide).

See also:

Your changes in static scope will live as long as your app

Static variables belong to type, not to its instance. And usually (if you are not creating multiple app domains) type objects are loaded only once and exist during the lifetime of the process.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!