Question

Using C#, asp.net in VWD 2010.

I have a session variable assigned manually in site.master (for testing purposes). I set the value as: Session["userid"] = (int) number

In my web page, I have the following code:

        litmsg.Text = "userid = " + Session["userid"].ToString();

        if (string.IsNullOrEmpty(Session["userid"] as string))
        {
            Session["errmsg"] = "No user ID is specified";
            litmsg.Text = litmsg.Text + "   inside loop";
          //  Response.Redirect("/PageError.aspx");
        }
        return;

During execution, the value in litmsg.Text is the correct user id, which tells me that Session["userid"] must have a value. However, if it has a value, then the string.IsNullOrEmpty() should return false, meaning the body should not be executed, and I should not see the phrase "inside loop."

The string.IsNullOrEmpty() also seems to fail in my PageError page:

 protected void Page_Load(object sender, EventArgs e)
 {
        if (!Page.IsPostBack)
        {
            string strErrMess = string.IsNullOrEmpty(Session["errmess"] as string) ? 
                   "Unspecificed error message" :
                    Session["errmess"].ToString();

            errmess.Text = strErrMess;
        }
}

In this case, it reports an unspecified message, even when I have set a value for Session["errmess"].

The thing is I use this idiom in other contexts and it seems to work - it's only when I apply it to the Session variable I have a problem. Is there something I'm missing

I have found references to a bug in PREVIOUS versions of the function when used with session variables, but those references indicate the bug has been fixed in current versions. For example, here: C# String.IsNullOrEmpty: good or bad?

I like this idiom, as I'm already using it in other places. Is there a better way of doing this? One that works? Or perhaps I'm doing something wrong.

Was it helpful?

Solution

try:

string strErrMess = (Session["errmess"] == null)
    ? "Unspecificed error message" 
    : Session["errmess"].ToString();

You are casting it as a string before testing if it's null, so it's throwing the error.

OTHER TIPS

If you cast an int to type string, it will result in a null reference, since it cannot be cast to that type. Therefore, the string.IsNullOrEmpty method will return true.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top