it has to do with memory usage and pointers. You have a stack, and a heap when allocating memory for objects, that memory is one the heap. Your saleItems variable is defined on the stack and points to the memory address on the heap. Your Dictionary is also on the stack pointing at the heap.
when you say:
saleItems = new List<SaleItem>()
the variable saleItems is pushed onto the stack and contains a memory address the points to the location of the data on the heap. Lets say 0x0100
. Now you add a new DictionaryItem
to your dictionary. The DictionaryItem
is placed on the heap with two properties, Key and Value. In this case, you have added saleItems
as Value
, so Value
has the address 0x0100
as well. Now DictionaryItem.Value
is pointing at the same memory as saleItems. When you call saleItems.Clear, you are saying find the list at address 0x0100
and remove all items. So the dictionary and the variable both become empty because they are pointing at the same memory. What you want to do is say saleItems = new List<SaleItem>();
again. Now saleItems will point to a new address on the heap (say 0x0200
). DictionaryItem.Value
is still pointing at memory address 0x0100
so you can act on the saleItems
variable without affecting the data in your dictionary.
For more information on stacks and heaps in c# try this article: http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91