Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone an ExpandoObject

Tags:

c#

dynamic

mvvm

wpf

This is for a MVVM based WPF project:

I am using an ExpandoObject in a view model for a dialog, which works very nicely since it implements INotifyPropertyChanged and I can bind to properties of the object directly in XAML.

However, to account for the user manipuating data but then hitting cancel I need to make a copy of the ExpandoObject to restore the original content.

In the dialog no properties are added to the object.

How can I clone it?

like image 874
Harald Avatar asked Apr 03 '14 02:04

Harald


People also ask

How do I know if I have ExpandoObject property?

For ExpandoObject, you can simply check whether the property is defined as a key in the underlying dictionary. For other implementations, it might be challenging and sometimes the only way is to work with exceptions.

How do I add properties to ExpandoObject?

// Add properties dynamically to expando AddProperty(expando, "Language", "English"); The AddProperty method takes advantage of the support that ExpandoObject has for IDictionary<string, object> and allows us to add properties using values we determine at runtime.

What is ExpandoObject in C#?

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject. sampleMember instead of more complex syntax like sampleObject.


1 Answers

Shallow copy:

static ExpandoObject ShallowCopy(ExpandoObject original)
{
    var clone = new ExpandoObject();

    var _original = (IDictionary<string, object>)original;
    var _clone = (IDictionary<string, object>)clone;

    foreach (var kvp in _original)
        _clone.Add(kvp);

    return clone;
}

Deep copy:

static ExpandoObject DeepCopy(ExpandoObject original)
{
    var clone = new ExpandoObject();

    var _original = (IDictionary<string, object>)original;
    var _clone = (IDictionary<string, object>)clone;

    foreach (var kvp in _original)
        _clone.Add(kvp.Key, kvp.Value is ExpandoObject ? DeepCopy((ExpandoObject)kvp.Value) : kvp.Value);

    return clone;
}
like image 71
talles Avatar answered Sep 30 '22 05:09

talles