2

I'm trying to perform a deep copy on a custom data structure. My problem is that the array (object[]) that holds the data I want to copy is of many different types (string, System.DateTime, custom structures etc). Doing the following loop will copy an object's reference, so any changes made in one object will reflect in the other.

for (int i = 0; i < oldItems.Length; ++i)
{
  newItems[i] = oldItems[i];
}

Is there a generic way to create new instances of these objects, and then copy any of the values into them?

P.s. must avoid 3rd party libraries

1
  • Would serialization suffice? Commented Dec 18, 2012 at 10:40

2 Answers 2

2

You can do that with automapper (available from Nuget):

object oldItem = oldItems[i];
Type type = oldItem.GetType();
Mapper.CreateMap(type, type);
// creates new object of same type and copies all values
newItems[i] = Mapper.Map(oldItem, type, type);
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming Automapper is out of the question (as @lazyberezovsky noted in his answer), you can serialize it for the copy:

public object[] Copy(object obj) {
    using (var memoryStream = new MemoryStream()) {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(memoryStream, obj);
        memoryStream.Position = 0;

        return (object[])formatter.Deserialize(memoryStream);
    }
}

[Serializable]
class testobj {
    public string Name { get; set; }
}

class Program {
    static object[] list = new object[] { new testobj() { Name = "TEST" } };

    static void Main(string[] args) {

        object[] clonedList = Copy(list);

        (clonedList[0] as testobj).Name = "BLAH";

        Console.WriteLine((list[0] as testobj).Name); // prints "TEST"
        Console.WriteLine((clonedList[0] as testobj).Name); // prints "BLAH"
    }
}

Note though: this would all be horribly inefficient.. surely there's a better way to do what you're trying to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.