I'm using extensively static variables in my web application project. Now I have read from some articles that it is a global variable for the whole project and the data that is in the static variables can be shared or overwritten by other users (I mean it is not user specific or session specific).
So is it general programming practice not to use static variables in the normal web application development?
Are static variables not used at all just like GOTO statement/keyword meaning there are extensive restrictions to use them and preferably not used at all? Then in what cases do we use the static key word?
Then i have this requirement that a particular variable has to be initialized only once in a particular webform.aspx.cs and the scope has to be restricted to only to that particular .aspx.cs and to that particular user who has logged in ? How do i meet this requirement ? If possible can any one illustrate this with code ?
Static variables are values that are also available across the whole application, but have some performance advantages and fewer overheads. The main difference to static variables and the previous examples is the fact that static variables are a side benefit of ASP.NET being object-oriented and the global being a .
A static variable is declared with the help of static keyword. When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are accessed with the name of the class, they do not require any object for access. Example: C#
1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can't be used for this purpose.
Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.
Personally I try to avoid static variables as much as possible. They make the code difficult to unit test and also could introduce subtle bugs due to concurrent access and race conditions.
As far as your requirement is concerned you could use store the variable as a property of the control in the ViewState. If it is user specific data that you are trying to store then you could use the Session state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With