0

I can't see what's wrong with this code:

var listShoppingCart = Session["ShoppingCart"];

foreach (var item in listShoppingCart)
{

}

I get a red line below the listShoppingCart in the foreach loop. When I hover over the red line, the messages is that Foreach statement cannot operate on variables type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

I declare the list with a session like this:

Session["ShoppingCart"] = new List<Products>();

2 Answers 2

5

You need to cast the session object

var listShoppingCart = Session["ShoppingCart"] as List<Products>;

if (listShoppingCart != null)
{
    // Do stuff...
}

In the above code, we get the object located in the session at key "ShoppingCart" and cast that object to a List<Products>. If the cast cannot be done, then listShoppingCart will be null.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks the the help!
0

Because Session is of Type HttpSessionState and this implements ICollection. Session values are stored in Dictionary<string,object> which implements ICollection. You need to type cast object to appropriate to enumerate over your list.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.