Harald Harald - 9 months ago 98
C# Question

How to clone an ExpandoObject

This is for a MVVM based WPF project:

I am using an

in a view model for a dialog, which works very nicely since it implements
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
to restore the original content.

In the dialog no properties are added to the object.

How can I clone it?

Answer Source

As a remaining believer in static typing, eugh...

That being said, it looks like ExpandoObject implements IDictionary<string, object>:

dynamic foo1d = new ExpandoObject();
foo1d.a = "test";

dynamic foo2d = new ExpandoObject();
foreach (var kvp in (IDictionary<string, object>)foo1d)
    ((IDictionary<string, object>)foo2d).Add(kvp);

Debug.Assert(foo1d.a == foo2d.a);

or in VB:

Dim foo1d As Object = New ExpandoObject
Dim foo2d As Object = New ExpandoObject
foo1d.a = "foo"

Dim cloneDictionary = CType(foo2d, IDictionary(Of String, Object))
For Each line In CType(foo1d, IDictionary(Of String, Object))
    cloneDictionary.Add(line.Key, line.Value)

I will note that this is only a shallow clone. You would have to do further work do clone referenced objects.