Yanshof
Yanshof

Reputation: 9926

MemberwiseClone on object that contain Dictionary does not work

I have some object that contain Dictionary - i trying the MemberwiseClone - but this return a new object but on the Dictionary i get reference on the original Dictionary object and not a copy.

Why ? How to make a simple clone of my object without using foreach on the original Dictionary and put the original object of the Dictionary in the new Dictionary ?

Upvotes: 1

Views: 1695

Answers (1)

Eugene Podskal
Eugene Podskal

Reputation: 10401

MSDN says that Object.MemberwiseClone:

Creates a shallow copy of the current Object.

As it has been already pointed by @firda shallow copying does not create deep copy of every field - it creates superficial copy - What is the difference between a deep copy and a shallow copy?.

Shallow copying for object references stored in the fields of your object means that only the value of the reference("pointer") will be copied to new object. So, in your case the Dictionary referenced in the field will not be actually copied(cloned) - the field in both the old and cloned object will still reference the same old Dictionary.

That is the same principle like in usual assignment - C# Reference type assignment VS value type assignment.

P.S. C# and .NET does not provide any simple and native ways to organize deep copying. You could try to use some 3rd party tools or manually implement the method - Deep cloning objects

Upvotes: 3

Related Questions