Int-session variable to increase?

Can a session variable be int ? I want to increase Session["PagesViewed"]+1; every time the page loads. I get errors when trying to increase the value of a session variable.

 if (Session["PagesViewed"].ToString() == "2") { Session["PagesViewed"] = 0; } else { Session["PagesViewed"]++; } 
+4
source share
3 answers

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

You can increment as follows.

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

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

 if (Session["PagesViewed"] != null) Session["PagesViewed"] = ((int)Session["PagesViewed"]) + 1; 
+8
source

Session["PagesViewed"] returns an Object, so your .ToString() call works. You will need to return this back to int, increment it there, and then return it back to the session.

+2
source

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

You can tell the compiler that you will not do something like this by casting: you will get an exception at runtime if the session variable is not really int.

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

Source: https://habr.com/ru/post/1388758/


All Articles