tags:

views:

55

answers:

4

In C#, the following "containers" hold reference or object itself for reference types?

Queue
Stack
Array
List
Vector

For example if I do the following:

Queue<MyItem> item = new Queue<MyItem>(100);
MyItem mit = new MyItem();
item.Enqueue(mit);

The reference of the mit is copied to item or the mit object itself has been moved to item memory location?

if I say

item = null;

it will not set all objects inside item to null. Am I right?

+3  A: 

The Queue contains a reference to the items in contains. Setting the Queue to null will not affect the items themselves.

Adel Hazzah
Other containers are the same?
5YrsLaterDBA
@5YrsLaterDBA yes as long as the items are reference types
msarchet
+1  A: 

It depends on whether the MyItem is a value type (sometimes called struct after the keyword) or refernce type (class). Value type assignments copy the value (i.e. the whole object) while reference types copy the reference.

Stilgar
A: 

The reference of the mit is copied to item or the mit object itself has been moved to item memory location?

  • First of all, I think you're caring way too many about implementaion details.

  • "The reference of the mit" is kinda meaningless. "mit" is a reference. If I add mit2 = mit;, both mit & mit2 reference the same object.

  • Similarly, moving "the mit object itself ... to item memory location" isn't really meaningful in managed code. If I add item.Enqueue(mit2);, item now has two entries pointing to the same object.

James Curran
A: 

The reference of the mit is copied to item or the mit object itself has been moved to item memory location?

Not really. If the object in question is a reference type then it is neither moved nor copied. It is more precise to say that a new reference to the same object has been added to the collection. If the object is a value type then it is indeed copied.

if I say item = null; it will not set all objects inside item to null. Am I right?

You are correct. It will not do anything to the items contained within the collection regardless of whether they are reference or value types.

Brian Gideon