GuyMontag GuyMontag - 9 months ago 54
C# Question

Copying objects without keeping a reference

Background: I have a list of objects that are directly linked to the UI in WPF. I need to do some work with those objects, but while I am working with them (asynchronously) I do not want any refreshes on the UI (performance and aesthetic reasons).

So I thought, I might copy the items (using

Collection<T>.CopyTo(T[] array, int index)
), work on the copy, then override my original list with the copied one. The problem is, that even then the reference are kept and the UI is continuously refreshed.
Code example of what I did:

MyUIObject[] myCopiedList = new MyUIObject[MyObjectsLinkedToTheUI.Count];
foreach (MyUIObject myCopiedItem in myCopiedList)
//while I do this, the UI is still updated
foreach (var myCopiedItem in myCopiedList)

Is there a possibility to copy my items without keeping a reference to the original object?


Thank you for your contributions so far. One thing I forgot to mention: This is for Windows Phone 8.1, so ICloneable is not available.

Vir Vir
Answer Source

You need to clone them somehow. Either implement ICloneable interface and do all rewriting manually or you can use some hacks/tricks like serializing and deserializing object.

Flow with serialization is something like this:

  1. Take your object
  2. Serialize it to, for example, JSON, binnary format etc.
  3. Now deserialize what you got in step 2 into new object

You'll have a copy of your object that way but it costs more processing power and is prone to some hard to catch errors. But it's an easy way to go. Thing with implementing ICloneable is more reliable but you need to write all that mapping by yourself.

Also, consider using structs instead of classes. Structs are always copied by value not reference. It has some drawbacks so it's up to you if they suit your usage scenario.