I always thought that objects where always passed as reference in C# and that if a function modifies it then the parent method should have a modified version of that object. However, reading this code that was left by an old developer that was causing a bug makes me think that this is not always the case. The code is the following:
Item item = new Item();
PopulateItem(sodItem, id, item);
The function code is the following:
private void PopulateItem(eSodTypes.Item sodItem, int id, Item item)
{
if (sodItem != null)
{
item = (Item)sodItem;
item.Delivery = (Delivery)sodItem.Delivery;
if (sodItem.Delivery != null)
{
item.Delivery.DeliveryContact = (CustomerContact)sodItem.Delivery.DeliveryContact;
item.Delivery.DeliveryAddress = (Address)sodItem.Delivery.DeliveryAddress;
item.Delivery.ShippingInstructions = (ShippingInstructions)sodItem.Delivery.ShippingInstructions;
}
item.Installation = (Installation)sodItem.Installation;
item.Training = (Training)sodItem.Training;
item.Service = (Service)sodItem.Service;
item.Service.Address = (Address)sodItem.Service.Address;
if (sodItem.Service.Address != null)
item.Service.Address.Contact = (CustomerContact)sodItem.Service.Address.Contact;
item.Service.Customer = (Customer)sodItem.Service.Customer;
if (sodItem.ItemLines != null)
item.ItemLines = sodItem.ItemLines.Items.ToList().ConvertAll(new Converter<eSodTypes.ItemLine, ItemLine>(ItemLine.ItemLineTypeToItemLineTypeModel));
}
}
If I use “ref” with the item it works, but I thought this was only for value types like “int” or “double”.
I’m assuming you mean that you expect that ‘item’ will be modified upon return from the method. The problem is here:
You’re modifying the variable item to point to the parameter sodItem, so it’s no longer pointing to the same item that was passed in. The original reference ‘item’ was never modified. When you change the item parameter to ‘ref’, this does cause the original reference of the variable passed as a parameter to change.
Note that this current code is actually modifying the original sodItem (copying its own values back to itself), which might not be your intention.