nf313743
nf313743

Reputation: 4227

Create new instance of an object from an array of unknown types

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

Upvotes: 2

Views: 1376

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65049

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.

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

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

Upvotes: 2

Related Questions