Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle ((List<string>)Session.Add("")

((List<string>)Session["answera"]).Add(xle.InnerText); 

I need to perform this operation, but I get "Object reference not set to an instance of...." I don't want to use

 List<string> ast = new List<string>();
    ast.Add("asdas!");
    Session["stringList"] = ast;
    List<string> bst = (List<string>)Session["stringList"];

as I merely want to add a string to the Session-String-Array.

like image 598
dll32 Avatar asked Feb 27 '23 11:02

dll32


1 Answers

Have you thought about wrapping your List<string> in a property of a custom context object? I had to do something like that on an application, so I ended up creating what was for me a UserContext object, which had a Current property, which took care of creating new objects and storing them in the session. Here's the basic code, adjusted to have your list:

public class UserContext
{
    private UserContext()
    {
    }

    public static UserContext Current
    {
        get
        {
            if (HttpContext.Current.Session["UserContext"] == null)
            {
                var uc = new UserContext
                             {
                                 StringList = new List<string>()
                             };

                HttpContext.Current.Session["UserContext"] = uc;
            }

            return (UserContext) HttpContext.Current.Session["UserContext"];
        }
    }

    public List<string> StringList { get; set; }

}

I actually got most of this code and structure from this SO question.

Because this class is part of my Web namespace, I access it much as I would access the HttpContext.Current object, so I never have to cast anything explicitly.

like image 133
Josh Anderson Avatar answered Mar 01 '23 09:03

Josh Anderson