How to avoid methods operating on duplicate objects

Hi everyone,

I am working on a series of custom c# components making use of custom classes and objects wrapped in Goo transferred between components.

In my component, I would create a Goo object to save the input data and a new object extracting the duplicate of the value. For example something like this:

CustomClass item = new CustomClass();
CustomClassGoo itemgoo = new CustomClassGoo();
DA.GetData(0, ref itemgoo);
item = itemgoo.Value.Duplicate();

This is how the Duplicate() method would be implemented:

public CustomClass Duplicate()
CustomClass item = new CustomClass();
item.ID = ID; = name;
return item;

I essentially create a new object, copy all the properties and return this new object.

I have now realised that after using item = itemgoo.Value.Duplicate(), when I call methods on it, this methods change the object that is passed as input. To explain myself better, in component 1 I create an object and I feed it in component 2; in component 2 I create a duplicate of the object and then call some methods; these methods have effect on the object created in component 1.

How can I avoid this?

Many thanks

Hi, you need to create a deep copy of your object, meaning no reference in memory will longer exist and the copy will be an independent copy.

1 Like

Thanks a lot for this!

I am still learning C# and missed the difference between a shallow and a deep copy. It required a decement amount of manual work, but I adjusted the Duplicate() method and other ones, and it seems to work as expected now.

No need to reinvent the wheel. Programmers have been solving problems many years ago.