Reputation: 75103
I'm reusing a created Object just to change a Date and the ordinal value, but at the end I get 6 objects exactly as the last.
in other words, I'm adding the object as a Reference and I should add as a Value
What should I inherit my Object to have the Copy()
method ?
RecurringPayment rp, copy;
rp = new RecurringPayment
{
...
}
payments.Add(rp); // add first object
copy = rp; // Copy the original element
for (int i = 1; i <= 5; i++)
{
copy.NextPaymentDate = copy.NextPaymentDate.AddDays(copy.RecurringTime * 7);
copy.OrderOrdinal = copy.OrderOrdinal + 1;
payments.Add(copy); // add 5 more with X weeks ahead
}
Thank you
Upvotes: 2
Views: 142
Reputation: 1502276
You don't end up with 6 objects. You end up with 6 references all of which refer to the same single object.
You could implement ICloneable
, and call Object.MemberwiseClone
- but I'm not sure I would. Instead, I'd be tempted to try to make RecurringPayment immutable to start with, and add a method WithNextPaymentDate(DateTime nextDate)
or something similar, which creates a new object with the given values. Your code would then be something like this:
// Can't use object initializers on immutable types of course - all the
// values would have to be specified in the constructor call
RecurringPayment payment = new RecurringPayment(...);
payments.Add(payment);
for (int i = 1; i <= 5; i++)
{
// This would automatically increment the OrderOrdinal in the newly
// created object
payment = payment.WithNextPaymentDate(payment.RecurringTime * 7);
payments.Add(payment);
}
Upvotes: 2
Reputation: 21900
You can implement ICloneable and then call clone to get a shallow copy of your object!
You can implement like this if you want(there are probably better ways out there):
public object Clone()
{
return MemberwiseClone();
}
Upvotes: 3