How to convert Session Variable to Integer Type in C#

Sorry Guys,

I just changed the integer converting code from

((int) Session["LoginAttempt"])

to

Convert.ToInt32(Session["LoginAttempt"]) + 1;

and now it is working fine for me, please suggest incase of any issues in it.

Thanks!


Try the magic code:

Session["LoginAttempt"] = ((int?)Session["LoginAttempt"] ?? 0) + 1;

This will convert the session variable Session["LoginAttempt"] to a nullable int (an int that can be null) the ?? 0 provides a value 0 if it is null, so the calculation succeeds.

The Session["LoginAttempt"] can be null if it is not initialized before.


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

Here you are doing an increment:

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

But, if the Session["LoginAttempt"] does not exist, this will explain your error. A quick null test before the increment should sort it out.

if (Session["LoginAttempt"] != null)
    Session["LoginAttempt"] = ((int)Session["LoginAttempt"]) + 1;

Tags:

C#