Zo Has
Zo Has

Reputation: 13038

Check for Session before returning it?

Hello guys I have a function inside a utility class which returns the current session User ID. It throws object reference not set to instance of object ? How do I check it for null & remove this error ?

public static string GetSessionUserID
{
    get
    {
        string userID = "";
        if (System.Web.HttpContext.Current.Session["userID"].ToString() != null)
        {
            userID = System.Web.HttpContext.Current.Session["userID"].ToString();
        }
        if (userID == null)
        {
            throw new ApplicationException("UserID is null");
        }
        else
            return userID;
    }
}

Upvotes: 1

Views: 1093

Answers (2)

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

object userID = System.Web.HttpContext.Current.Session["userID"];
if (userID == null)
{
    throw new ApplicationException("UserID is null");
}
return userID.ToString();

If the object stored in the session is in fact already a string, you can dispense with the ToString. The cause of the error is simply that you can't call ToString on a null reference. That's why the above checks before doing so.

Upvotes: 6

D.J
D.J

Reputation: 2534

use "try" instead of "if"

string userID = "";
try{
            userID = System.Web.HttpContext.Current.Session["userID"].ToString();
}
catch{
            throw new ApplicationException("UserID is null");
}
return userID;

Upvotes: 0

Related Questions