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?

user1352057
  • 3,162
  • 9
  • 51
  • 117

2 Answers2

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
Chintana Meegamarachchi
  • 1,798
  • 1
  • 12
  • 10
0

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

nZeus
  • 2,475
  • 22
  • 21
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Nikolay Kostov Apr 24 '15 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 '15 at 22:02