0

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.

Community
  • 1
  • 1
elbillaf
  • 1,952
  • 10
  • 37
  • 73

2 Answers2

3

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.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • In my case, I reverse the sense to ==null || == "", but that works! Thanks! – elbillaf Oct 28 '13 at 14:05
  • sure thing. Always make sure you perform the null check first, as the right side won't be evaluated if that fails (and thus won't throw an exception) – Jonesopolis Oct 28 '13 at 14:09
1

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.

Maarten
  • 22,527
  • 3
  • 47
  • 68