ispiro
ispiro

Reputation: 27673

Why does this cloning not work?

I'm trying to clone instances of a derived class, but somehow it doesn't work well. The cloning method is:

public static T CloneFieldsAndProperties<T>(T input)
{
    T result = (T)Activator.CreateInstance(typeof(T));
    PropertyInfo[] listOfProps = typeof(T).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.CreateInstance);
    FieldInfo[] listOfFields = typeof(T).GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.CreateInstance);
    foreach (PropertyInfo prop in listOfProps) prop.SetValue(result, prop.GetValue(input, null), null);
    foreach (FieldInfo field in listOfFields) field.SetValue(result, field.GetValue(input));
    return result;
}

As you can see, I added many BindingFlags because it wasn't working. But to no avail.

It does work in a simple case:

MyclassA1 a1 = new MyclassA1();
MyclassA a = CloneFieldsAndProperties(a1);
if (a is MyclassA1) Text = "Works";

Where:

class MyclassA
{
    public int i;
}

class MyclassA1 : MyclassA
{
    public int i1;
}

But in my real program it doesn't. The real program's classes' declarations are long so I'm not posting them here. What might be the problem?

Upvotes: 1

Views: 1377

Answers (3)

Eli Arbel
Eli Arbel

Reputation: 22739

If you need a shallow clone, simply use Object.MemberwiseClone. If you need a deep clone, serialize and then deserialize your object (e.g. using JsonSerializer).

Upvotes: 2

lordcheeto
lordcheeto

Reputation: 1091

This will work and may be faster than the serialization method:

Code:

using System;

namespace Cloning
{
    class Program
    {
        static void Main(string[] args)
        {
            Derived d = new Derived() { property = 1, field = 2, derivedProperty = 3, derivedField = 4 };
            Base b = new Derived(d);

            // Change things in the derived class.
            d.property = 5;
            d.field = 6;
            d.derivedProperty = 7;
            d.derivedField = 8;

            // Output the copy so you know it's not shallow.
            Console.WriteLine((b as Derived).property);
            Console.WriteLine((b as Derived).field);
            Console.WriteLine((b as Derived).derivedProperty);
            Console.WriteLine((b as Derived).derivedField);

            Console.ReadLine();
        }

        class Base
        {
            public int property { get; set; }
            public int field;
        }

        class Derived : Base
        {
            public Derived() { }

            public Derived(Derived d)
            {
                // Perform the deep copy here.
                // Using reflection should work, but explicitly stating them definitely
                // will, and it's not like it's not all known until runtime.
                this.property = d.property;
                this.field = d.field;
                this.derivedProperty = d.derivedProperty;
                this.derivedField = d.derivedField;
            }

            public int derivedProperty { get; set; }
            public int derivedField;
        }

    }
}

Test:

http://goo.gl/pQnAL

Output:

1
2
3
4

Comments:

I would really imagine that this would work in more than just a trivial case but perhaps not:

public static T CloneFieldsAndProperties<T>(T input)
{
    T result = (T)Activator.CreateInstance(input.GetType());

    PropertyInfo[] properties = input.GetType().GetProperties();
    FieldInfo[] fields = input.GetType().GetFields();

    foreach (PropertyInfo property in properties)
        property.SetValue(result, property.GetValue(input, null), null);
    foreach (FieldInfo field in fields)
        field.SetValue(result, field.GetValue(input));

    return result;
}

Upvotes: 0

Tearsdontfalls
Tearsdontfalls

Reputation: 777

I had the same issue a long time ago. The only real solution for me, after lots of googling, was to serialize and deserialize it. It's not a bad solution and you lose only a little bit of performance, just do it like this:

Add this tag to your class:

[Serializable()]
public class a
{

}

And then you can create a function like this:

public object Clone()
{
    IO.MemoryStream mem = new IO.MemoryStream();
    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter form = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    form.Serialize(mem, this);
    mem.Position = 0;
    return form.Deserialize(mem);
}

Upvotes: 3

Related Questions