1

Question background:

I have a session object that is used to store a list of object called 'CartItems'. I convert this object to an actual instance, set it to another List variable then finally clear the list. This is then sent to to a ViewBag variable and sent to a View.

The issue:

What I'm trying to do may not be possible but currently as soon as I clear the list instance of CartItems all references to this are lost aswell. Please see the following code:

 public ActionResult Complete(string OrderId)
    {
        //Retrieve the CartItem List from the Session object.
        List<CartItem> cartItems = (List<CartItem>)Session["Cart"];

        //Set the list value to another instance.
        List<CartItems>copyOfCartItems= cartItems;

        //Set the ViewBag properties.
        ViewBag.OrderId = OrderId;
        ViewBag.CartItems = copyOfCartItems;

        //Clear the List of CartItems. This is where the **issue** is occurring.
        //Once this is cleared all objects that have properties set from
        //this list are removed. This means the ViewBag.CartItems property 
        //is null.
        cartItems.Clear();

        return View(ViewBag);
    }

Can I store this value without losing it after clearing the List?

3
  • 1
    You want to copy the List.
    – Jasen
    Apr 24, 2015 at 21:03
  • @Jasen many thanks that worked perfectly. If you set this as the answer I will mark it correct Apr 24, 2015 at 21:18
  • Chintana provided a good answer and reason.
    – Jasen
    Apr 24, 2015 at 23:28

2 Answers 2

1

When you do

ListcopyOfCartItems= cartItems;

You are creating a another variable by the name of copyOfCartItems that points to the same object cartItems. In other words cartItems and copyOfCartItems are now two names for the same object.

So when you do cartItems.clear(); you are clearing all the list items on the base object.

To get around this, make a copy of cartItems, rather than creating a reference

List<CartItems> copyOfCartItems = new List<CartItems>();

cartItems.ForEach(copyOfCartItems.Add); //copy from cartItems
0

If you want to clear Session["Cart"], use Session.Remove("Cart")

2
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. Apr 24, 2015 at 21:52
  • No, Nickolay, this can be an answer to the question. I assume that the author doesn't work correctly with the Session
    – nZeus
    Apr 24, 2015 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.