views:

43

answers:

2

Hi guys,

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

+3  A: 

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();
}
Oskar Kjellin
That's the easiest one :) Ty!
balexandre
+2  A: 

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);
}
Jon Skeet
wonder why you wouldn't choose the Clone() approach, any technical worry or was just to provide a new insight? Ty.
balexandre
@balexandre: I find immutable types easier to understand and work with. `ICloneable` is generally regarded as a bad interface: you have to cast the result as it returns just `object`, and there's no indication about whether it should perform a deep or shallow clone.
Jon Skeet
I will follow your recommendation :)
balexandre