I've been looking to implement a generic class that implements IEditableObject for some of my ViewModels to inherit in order to support cancellations of editings on the properties in that ViewModel. The primary use of this is for modal dialogs in WPF that has OK and Cancel buttons.
I've found the following implemetations online:
This seems overly complicated to me, but I'm unsure if I'm missing some of the functionality they provide. For one they don't support deep copy, so in my world we could just use MemberwiseClone to perform the shallow copy. Something like:
private Item backupCopy;
private bool inEdit;
public void BeginEdit()
{
if (inEdit) return;
inEdit = true;
backupCopy = this.MemberwiseClone() as Item;
}
public void CancelEdit()
{
if (!inEdit) return;
inEdit = false;
this.Name = backupCopy.Name;
}
public void EndEdit()
{
if (!inEdit) return;
inEdit = false;
backupCopy = null;
}
This example should of course be in a generic abstract base class for the ViewModels to inherit, but you get the idea...
What is the difference here? What are the disadvantages of my approach besides not supporting deep copy? How would you modify it to support deep copy (not really sure if it's necessary yet)?
Found this article showing a better implementation than mine using reflection. Still much simpler than the other two articles I linked to:
How can we extend this to support deep copy?
In fact, MemberwiseClone
applies a shallow copy. If you apply a shallow copy, reference type objects inside your object (like some reference type properties) are not created, just references are copied. So each instance will refer to the same objects.
In deep copy, reference type objects inside the object are also copied.
Think of a list of items; if you apply shallow copy, you will end up with two lists pointing to the same objects. If you apply deep copy, new objects will be created for the new list.
I advise you to go with deep copy, instead of a shallow copy. Think about the list example; if you apply a shallow copy and change any element in the copied list, then it will not be possible to revert all changes back; since copied list shares the same elements with the original list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With