4

I'm trying to add an object(s) to a session variable across postbacks. My code looks similar to the following.

  Supply sup =  Supplies.GetSupply(supplyItemID);

  Session["CartObjects"] += sup;

Now, the compiler throws an error saying that the "+=" operator cannot be used on type 'object' and 'Supply'. Do I need to implement an interface on my Supply object that allows it to be added? Is this possible or am I thinking about this in the completely wrong way.

John Czajka
  • 183
  • 1
  • 1
  • 11

3 Answers3

12

Try this:

Supply sup =  Supplies.GetSupply(supplyItemID); 
var cartObjects =  (Session["CartObjects"] as List<Supply>) ?? new List<Supply>();
cartObjects.Add(sup);
Session["CartObjects"] = cartObjects;
Chandu
  • 81,493
  • 19
  • 133
  • 134
7

unless you are trying to create some sort of array the syntax is just

Session["CartObjects"] = sup;
Gary.S
  • 7,076
  • 1
  • 26
  • 36
2

No You dont need ,just Create a List of Supply and Save it in session

var supplyList = new List<Supply >();
Supply sup =  Supplies.GetSupply(supplyItemID);
supplyList.Add(sup);
Session["CartObjects"] =supplyList;

and 
and cast it as supply List
var list = Session["CartObjects"] as List<Supply >
DeveloperX
  • 4,633
  • 17
  • 22