Tuesday, August 3, 2010

Static variables Versus Session variables

Static variables Versus Session variables:

Let me explain you something which I came across in a project when it went to production. I was working for a project called timesheet and during its code implementation I used some static variables because I was in confident of the following things:

1) Static variables persist there value and there scope is within the session.

2) Static variables are destroyed once the session of the user is destroyed.

I was very sure that static variables will persist values for different function calls and they will not be availble across sessions. This made me very unabashed for sometime because many production issues were reported by users while they were submitting their timesheet request. One of my senior asked me, did you use static variables in you code? I said yes, and then he immediately took attention and asks me to go through the code and remove all static variables until unless they are to be used across different user’s session. Use session instead of static variables if information is user specific.

Static variables: We know that static variables persists values between different function call and it is very true. The nature of static variables in C# is at application level and you know that application level is always higher than session.

Static variables are visible and persists their values across different user’s sessions. They are intialize as soon as the application start running on IIS and they remain till IIS server (in case of ASP.net application) is reset.

Session variables: Session variables scope is below application level. A web application running can have one or more user’s session running. The session is destroyed explicitly or when the client browser is closed.

Note that having one browser open and multiple tab is been treated as same session. Different instance of browser will have different sessions for you.

1 comment: