Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Session Variable to Integer Type in C#

Tags:

c#

I am using C#

I am trying to check whether my login attempt is not more than 3, I mean with the below condition:

if (((int)Session["LoginAttempt"]) != 3)
{
}

In Login failed condition I am doing increment like below:

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

But it is giving me this error: "Object reference not set to an instance of an object."

Suggestions please!

like image 701
Manoj Singh Avatar asked Feb 04 '11 10:02

Manoj Singh


4 Answers

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!

like image 174
Manoj Singh Avatar answered Sep 23 '22 16:09

Manoj Singh


Why not encapsulate the LoginAttempt value as a property and auto-assign a value:

protected int LoginAttempt
{
    get
    {
        if (Session["LoginAttempt"] == null)
        {
            Session["LoginAttempt"] = 1;
        }
        return Convert.ToInt32(Session["LoginAttempt"].ToString());
    }
    set
    {
        Session["LoginAttempt"] = value;
    }
}

so that the main body of the function is more readable:

if (LoginAttempt < 3)
{
}
like image 28
Dave Avatar answered Sep 21 '22 16:09

Dave


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.

like image 26
GvS Avatar answered Sep 24 '22 16:09

GvS


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;
like image 29
Neil Knight Avatar answered Sep 21 '22 16:09

Neil Knight