How do I copy an instance of an object?

.net, c#, oop

Solution

Then you need to implement `ICloneable` and replace

r.TryAddPackage((IPackage)ps);

with

r.TryAddPackage((IPackage)ps.Clone());

It's up to you to decide how `Clone` should populate the new instance of `PinnacleStock` that it returns.

At the most basic level, you could say

public PinnacleStock : ICloneable {
    public PinnacleStock Clone() {
        return (PinnacleStock)this.MemberwiseClone();
    }
    object ICloneable.Clone() {
        return Clone();
    }
    // details
}

This will just do a shallow copy of `PinnacleStock`. Only you know if this is the correct semantics for your domain.

Problem

I'm trying to write some code that populates a `List` (actually, it's a series of `Lists`, but we can pretend it's just one `List`). The idea is to add an `IPackage` to the `List` for the total quantity of `IPackage` on order. See the following code: ``` ParseExcel pe = new ParseExcel(); Pinnacle p = pe.ParsePinnacleExcel(); Rack r = new Rack(20,2,4.5,96,42,6,25*12); foreach (PinnacleStock ps in p.StockList.Where(x => x.ColorCode == "10" && x.PackageLength == 30.64)) { for (int i = 1; i <= ps.OnOrder; i++) { r.TryAddPackage((IPackage)ps); } } ``` Everything seems to be working well, insofar as the `IPackage` is repeatedly added to the list. However, it seems that the same instance of the object is being added, i.e. the object is not being copied each time it's added to the list. What do I need to do to ensure that a copy of the object is inserted into the list, and not just an additional reference?

Original source

Related problems