Duplicate Object and working with Duplicate without changing Original

C#

C# Problem Overview


Assuming I have an Object ItemVO in which there a bunch of properties already assigned. eg:

ItemVO originalItemVO = new ItemVO();
originalItemVO.ItemId = 1;
originalItemVO.ItemCategory = "ORIGINAL";

I would like to create another duplicate by using :

duplicateItemVO = originalItemVO;

and then use the duplicateItemVO and alter its' properties, WITHOUT changing the originalItemVO:

// This also change the originalItemVO.ItemCategory which I do not want.
duplicateItemVO.ItemCategory = "DUPLICATE" 

How can I achieve this, without changing the class ItemVO ?

Thanks

public class ItemVO     
{
    public ItemVO()
    {
        ItemId = "";
        ItemCategory = "";
    }

    public string ItemId { get; set; }
    public string ItemCategory { get; set; }
}

C# Solutions


Solution 1 - C#

You would need to construct a new instance of your class, not just assign the variable:

duplicateItemVO = new ItemVO 
    { 
        ItemId = originalItemVO.ItemId, 
        ItemCategory = originalItemVO.ItemCategory 
    };

When you're dealing with reference types (any class), just assigning a variable is creating a copy of the reference to the original object. As such, setting property values within that object will change the original as well. In order to prevent this, you need to actually construct a new object instance.

Solution 2 - C#

In order to change one instance without changing the other you need to clone the actual values of this instance and not the reference. The pattern used in .Net is to implement ICloneable. So your code would look like this:

public class ItemVO: ICloneable
  {
    public ItemVO()
    {
        ItemId = ""; 
        ItemCategory = ""; 
    }
   
    public string ItemId { get; set; }
    public string ItemCategory { get; set; }

    public object Clone()
    {
        return new ItemVO
        {
            ItemId = this.ItemId,
            ItemCategory = this.ItemCategory
        }; 
    }
 }

Now notice that you need an explicit cast when using Clone() (or you can make your own that returns ItemVO).

duplicateItemVO = (ItemVO) originalItemVO.Clone(); 

Solution 3 - C#

To duplicate an object by value instead of reference, you can serialize it (e.g. JSON) and then deserialize it right after. You then have a copy by value.

Here's an example

ItemVO originalItemVO = new ItemVO();
originalItemVO.ItemId = 1;
originalItemVO.ItemCategory = "ORIGINAL";

string json = Newtonsoft.Json.JsonConvert.SerializeObject(originalItemVO); 
ItemVO duplicateItemVO = Newtonsoft.Json.JsonConvert.DeserializeObject<ItemVO>(json);

Solution 4 - C#

You cannot practically copy an object since they would more likely be of reference types. The ideal method is to serialize or stream the object into a new one - Provided your class is serializable (by providing the [Serializable] attribute in class declaration).

private static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }

        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }

Now you can use this code:

[Serializable]
public class MyClass
{
  public int a {get; set;}
  public int b {get; set;}
}     

var obj = new MyClass{
a = 10,
b = 20,
};

var newobj = Clone<MyClass>(obj);

You will get an entirely new copy of obj. Note: Any other class inside MyClass must also be declared with the attribute [Serializable].

Solution 5 - C#

I suggest using as is in the link below. For me it worked very well.

https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx

 public Person ShallowCopy ()
 {
    return (Person) this.MemberwiseClone ();
 }

Solution 6 - C#

class are reference type and when you change one instance it will change the ariginal refference. so use value type object for overcome your task(ex: use struct instead of class)

public struct ItemVO { *** }

or you can implement ICloneable Interface for your class

Solution 7 - C#

By Default objects are reference type.

Assign the one object to another object its means that you just refer the address of the object.Any changes in any object it will reflect in both.

To solve this problem you should have initialize the object using "new" keyword, then add this object value in the first object.

Solution 8 - C#

As of c# 4.5 the base class object contains a method called MemberwiseClone that enables you to perform a shallow copy of that object and returns the result as a new instance. (If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.)

This is useful if you are looking to implement a prototype design pattern.

If you are looking to implement a deep copy (everything within the class is duplicated as new instances) then serialization or reflection are probably the best tools

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGotchaView Question on Stackoverflow
Solution 1 - C#Reed CopseyView Answer on Stackoverflow
Solution 2 - C#Sofian HnaideView Answer on Stackoverflow
Solution 3 - C#AmitView Answer on Stackoverflow
Solution 4 - C#Venugopal MView Answer on Stackoverflow
Solution 5 - C#Luiz BaiãoView Answer on Stackoverflow
Solution 6 - C#Chamika SandamalView Answer on Stackoverflow
Solution 7 - C#Partha RanjanView Answer on Stackoverflow
Solution 8 - C#Jamie PearceyView Answer on Stackoverflow