Global variables in C# Using Static Variables Vs Application Cache

Posted by Hardcoder under C# category on | Views : 31533
Some times we need to use some variable globaly so that it may be available to application wide. For having a global variable we can use static variables as well application cache.

Example :

Application["gVar1"]="Global variable One stored here";
and this can be get anywhere in application by using string var1 = (string)Application["Var1"];

The same thing can be by using static variable also.

public static string GVar2;

These variables need to be initialized first time into Global.asax.cs application_start() method and keep alive until a IIS reset or worker process recycle not occurs.

Application["gVar1"]="Global variable One stored here";
Gvar2= "Global Variable Two is here";
For using the Gvar2 we need to simply write the className.Gvar2 // Here Global.Gvar2 will do the work for us.

So the question arise as both are doing the same work which we prefer to use.
I must say It depends!!

Why I said so? Because there are reasons behind this.
In the above scenario I must say I MUST use static variable. (Please make static property rather than directly using static variable)
So what factors you must count for choosing static -
1. Application holds variable as Object.
2. While getting the value we need to caste into the objects which it stores. Of course casting need some value.

So when we need to use some primitive variables and they are not going to changes very frequent (locking issue in case of frequent changes) we should use static variable.
Application need to be used when we need to Hold some objects application wide.
(Note Its my own experience please do not take it as hard and fast rule).


Comments or Responses

Login to post response