collection copy behavior question
in c#, after I add a object to a collection, if another copy(deep copy) is always cre开发者_运维知识库ated?
No, if it is a class, most objects are, only a reference to the same object is stored in the collection.
If it is a value type, like int, double and structs a copy is made (not a deep copy, if the struct has a reference to a class object that in turn will not be copied).
Edit:
To deep copy objects you first need to create a deep copy function.
Have a look at Create a Deep Copy in C# or How to make a deep copy in C# ?
Then you can run your deep copy method before adding items to your collection.
Note
It is not very often you really need a true deep copy. Often it is better to rethink the dataflow in your application.
If you are asking about what happens with the collection, then it depends:
Normally, a collection will be created with some "empty" slots, so adding to it will not cause a new collection with a new size to be created.
If, however adding a new item goes beyond this size, a new collection will be created and all items copied to it.
If you are asking about the item itself, again it depends:
If it is a value type (int, double, structs for example), then the value will be copied, if it is a reference type, a copy of the reference to the same object will be used.
精彩评论