Duplicate Object and working with Duplicate without changing Original
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; }
}
Solution 1:
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:
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();