Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IEditableObject implementations

Tags:

c#

wpf

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:

  • Generic implementation of IEditableObject via TypeDescriptor and Reflection
  • Paul Stovell: IEditableObject Adapter for WPF and Windows Forms

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)?

Update:

Found this article showing a better implementation than mine using reflection. Still much simpler than the other two articles I linked to:

  • Reusable EditableModelBase using IEditableObject

How can we extend this to support deep copy?

like image 647
Tommy Jakobsen Avatar asked Feb 21 '13 08:02

Tommy Jakobsen


1 Answers

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.

like image 153
daryal Avatar answered Nov 12 '22 06:11

daryal