5

Can a session variable be an int? I want to increment Session["PagesViewed"]+1; every time a page is loaded. I'm getting errors when trying to increment the session variable.

if (Session["PagesViewed"].ToString() == "2")
{
     Session["PagesViewed"] = 0;
}
else
{
     Session["PagesViewed"]++;
}
3
  • What are the errors you're getting? Commented Dec 31, 2011 at 20:24
  • You need to make sure you are not in a webfarm. If so, verify that you have shared session. Also, kind of off topic, but google analytics does this for you and probably more efficiently. Commented Dec 31, 2011 at 20:33
  • 1
    Session["PagesViewed"]++; is basically the same as ((object)Session["PagesViewed"])++; and is not legal. Commented Dec 31, 2011 at 20:38

3 Answers 3

8

You need to test to see if the Session variable exists before you can use it and assign to it.

You can do increment as follows.

Session["PagesViewed"] = ((int) Session["PagesViewed"]) + 1;

But, if the Session["PagesViewed"] does not exist, this will cause errors. A quick null test before the increment should sort it out.

if (Session["PagesViewed"] != null)
    Session["PagesViewed"] = ((int)Session["PagesViewed"]) + 1;
Sign up to request clarification or add additional context in comments.

2 Comments

That won't compile. You need to explicitly add the 1: Session["PagesViewed"] = (int)Session["PagesViewed"] + 1;
Should probably use ++ as a prefix since it does an assignment first as a postfix and so the value will not change. Session["PagesViewed"] = ++((int)Session["PagesViewed"]);
3

Session["PagesViewed"] will only return an Object - which is why your .ToString() call works. You will need to cast this back to an int, increment it there, then put it back in the session.

Comments

2

Yes, it can be. However, ++ only works when the compiler knows the object is an int. How does it know that some other part of your code doesn't sneakily do Session["PagesViewed"] = "Ha-ha";?

You can effectively tell the compiler that you won't do something like that by casting: you'll get a runtime exception if the session variable isn't really an int.

int pagesViewed = (int)Session["PagesViewed"];
if (pagesViewed == 2)
{
    pagesViewed = 0;
}
else
{
    pagesViewed++;
}
Session["PagesViewed"] = pagesViewed;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.