Why does this code result in both shipment.Items.Count and combinedShipment.Items.Count equal to zero?
private static InboundShipment CombineLikeIsbns(InboundShipment shipment)
{
// shipment.Items has a count of 3
var distinctIsbns = shipment.Items.Select(i => i.ISBN).Distinct().ToList();
var combinedShipment = shipment;
combinedShipment.Items = new List<InboundShipmentItem>();
// Now both combinedShipment and shipment have an empty List in the .Items property
...
return combinedShipment;
}
[EDIT]
And what can I do to avoid having shipment.Items set to new List when I set combinedShipment.Items to the same?
This statement:
copies the value of
shipmentintocombinedShipment. AssumingInboundShipmentis a class, the value ofshipmentis a reference – not an object itself.So now we have two variables which both refer to the same object. It doesn’t matter which variable you use to make a change to the object – the change will be visible via both variables.
If you want to create a new “copy” of the original object, you’ll have to do that explicitly. It’s hard to know exactly what you’d need to do here, as you haven’t given us much information about the
InboundShipmenttype.See my article on value types and reference types for more details. Note that this is a vital part of C# and .NET, and you should become confident on it before going further – advanced topics such as LINQ (with its lambda expressions, deferred execution etc) will be hard to understand until you’ve got a good handle on the basics.