0

I have code as follows:

var feeCTC = new FeeGroup(); feeCTC = feeGroup;
var feeWYS = new FeeGroup(); feeWYS = feeGroup;
feeCTC.FeeValue = 231;
firstList.Add(feeCTC);
feeWYS.FeeValue = 1269;
secondList.Add(feeWYS);

The problem I'm coming across is that once I get to the second calcuation that sets feeWYS.FeeValue, feeCTC.FeeValue is also updated to the same number (and so is its value in firstList), which leads me to believe that they are references to the same address. How do I clone feeGroup so that I can manipulate its values (and without using ICloneable interface)?

hengj
  • 87
  • 1
  • 1
  • 10

1 Answers1

1

feeCTC = feeGroup; does NOT clone feeGroup. It copies the reference to feeCTC. So both feeCTC and feeWYS are referencing the same object. That's why any changes you make thorugh one reference are reflected in the other reference.

How do I clone feeGroup so that I can manipulate its values (and without using ICloneable interface)?

Some options:

  • Write a clone method that copies the properties individually (making sure you close reference types as well)
  • Write a copy constructor that does the same thing, just within a constructor. One benefit of a copy constructor is that you can access private fields of both objects, which may be handy in some situations.
  • Use Object.MemberwiseClone to make a shallow copy (again making sure you close reference type properties.
  • Serialize the object to a memory stream and deserialize it.

Note that IClonable is pretty well useless since all it defines is a Clone method but provides no implementation or context to indicate if the close is a shallow or deep clone.

Community
  • 1
  • 1
D Stanley
  • 149,601
  • 11
  • 178
  • 240