copying collection of value types

  • Thread starter Thread starter shumaker
  • Start date Start date
S

shumaker

If I create a new collection from a colelction containing only value
types, will the value types be copied, or will both collections
reference the same value types. Such as:

new Dictionary<string, byte[]>(aDictionaryCollection);


Will "aDictionaryCollection" and the new Dictionary reference the same
items such that if I modify a value in one then it will affect both?
 
Value-types will be silently copied both in the collections, and also
every time you access them. However, even though byte is a value-type,
byte[] is a reference type.

This means that:
aDictionaryCollection["abc"][5] = 123; // assign 123 as the 6th byte
against key "abc"
byte test = newDict["abc"][5]; // read the 6th byte from key "abc" in
the new dictionary

Here test should be 123, since aDictionaryCollection["abc"] and
newDict["abc"] are looking at the same byte[] instance.

However, if you *reassign* the *array* in one of the dictionaries, then
they will become divorced:

newDict["abc"] = new byte[] {1,2,3,4,5}; // now the abc byte[] in
newDict is different

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top