tags:

views:

58

answers:

2

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;
    }
}
+5  A: 
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.

Matthew Flaschen
Thanks Matthew. The explanation was really helpful. Did you meant object instead of var ?
Popo
@Popo, they should be equivalent (the compiler will replace `var` with `object`). However, I agree that `object` is clearer here.
Matthew Flaschen
Thank you Matthew. I prev. thought var only existed in javascript.
Popo
A: 

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;
D.J
^^ this isnt encouraged, why to add an unnecessary try catch block when it can be handled otherwise..
Dienekes
@Dienekes That is a interesting point, off the topic though. see the video http://www.youtube.com/watch?v=XcTKR_QhEoE. testing with bench marks has been done there. as well as http://stackoverflow.com/questions/1347848/c-real-time-try-catch Somehow i do agree with you, but it is not always necessary.
D.J