0

I am trying to clone an object in a way that i get a fresh copy of existing instance.

I am using AutoMapper like this:

Mapper.CreateMap(typeof(VariableSet), typeof(VariableSet));
var destinationObject = Mapper.Map<VariableSet>(command.VariableSets[0]);
command.VariableSets.Add(destinationObject);

I have an array:

command.VariableSets

I am trying to add another instance of the object that is at 0th index of this array. but when i use auto mapper it creates another instance by reference. So if i change any sub property in 0th index object, it also gets updated in 1st index object.

i tried cloning the object using serialization deserialization method but than i have to make my objects [Serializable] which has its own issue.

Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114
Raas Masood
  • 1,475
  • 3
  • 23
  • 61

1 Answers1

0

You can create new object manually and then map object-to-object:

var destinationObject = 
    Mapper.Map<VariableSet, VariableSet>(command.VariableSets[0], new VariableSet());

The same logic may be applied for each reference type property of VariableSet if you need to create new objects for it too.

Howewer, there are several ways to create an object's copy. For example you may implement ICloneable interface and then use Clone method. It gaves you full control of deep copying and don't require AutoMapper tool. You can find ton of information here:

Deep cloning objects

Community
  • 1
  • 1
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114