Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Enumerable.ToDictionary<TSource, TKey> perform a deep copy?

Tags:

c#

I would like to confirm that the answer to https://stackoverflow.com/a/10387423/368896 is correct and applies in the following case:

// These IDataHolder instances contains a property "name",
// and another data member that is a large array.
// A copy constructor exists that makes a deep copy.
public MyFunction(IEnumerable<IDataHolder> columns)
{
    // Is the copy constructor called?
    this.columns = columns.ToDictionary(c => c.info.name, c => c);
}

I am fairly confident that the copy constructor is not called; i.e., that the call to toDictionaary does not perform a deep copy but only copies references.

However, I cannot find confirmation of this.

Am I correct? Does toDictionary() perform a shallow copy only?

(Note: I have a strong C++ background, but am new to C#.)

like image 374
Dan Nissenbaum Avatar asked Oct 17 '25 01:10

Dan Nissenbaum


2 Answers

It will only copy over the object references and not perform any cloning (shallow, or deep) at all.

Normally, it will perform shallow copies of structs though just out of virtue of the pass-by-value semantics for structs. However in this case, since you have it typed as an interface, I do believe the value types will be boxed and not shallow copied.

If you need to perform your own deep copy of the elements, then you can use this overload and call the copy constructor yourself:

public MyFunction(IEnumerable<IDataHolder> columns)
{
    //replace c.DeepCopy() with whatever the deep copying function is
    this.columns = columns.ToDictionary(c => c.info.name, c => c.DeepCopy());
}

The main reason for this is because C# does not have a native, built-in method for deep copying*. This is typically to be implemented per-object as the developer needs.

* there are some ways to perform generalized deep copying which you can employ if your design warrants it

like image 162
Chris Sinclair Avatar answered Oct 19 '25 14:10

Chris Sinclair


No, the keys and values are both copied by value and this is a shallow copy.

Note, this is true regardless of the keys or values being value types or reference types.

For clarity, value types being copied by value means the fields are copied by value.

For additional clarity, for reference types, the references are copied by value. Since the references are copied by value, it's a shallow copy.

like image 20
jason Avatar answered Oct 19 '25 15:10

jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!