Tuesday, January 27, 2004

Session Variables in C# how to use them and win

So I have been hitting my head against the wall with Session variables in C#. For instance, you can see a variable by just calling it and giving it a value.  Session["myValue"] = value Which is kind of like working in VB.NET. However when you go to read values from there it is a different beast all together. This comes from the fact that Session variables are actually objects and can be set to just about anything. So if I am going to read a value out of the Session variable it looks something like this: Response.Write(Session["myValue"].ToString()); Okay, now so far this isn't to bad, but what VB and VB.NET programmers are not use to, is have to initate the Session that you are going to use later. For example you have a Session variable that only gets a value if a event happens. If that even happens you don't initate the variable. Later in your code you have a condition statement that checks against the value in your Session variable. In VB you can do this all day not, and if there value is empty (ie you didn't initate the Session variable)  it returns an empty or null value. However in C# you get an error stating that the Object has not be set.

So this got me, jumpin up and down flustered. Then Ed told me the secret to it all, and I will now share it with you. (Though I figured you have guessed it by now) Initate all of your Session variables in the Session_Start function in your Global.asax. This way they are always initated and if you run conditional statements against them you can get an empty or null value.

Happy Coding

No comments: