Tuesday, April 14, 2009

Copy Constructor Update

Stumbled upon a problem today and understood that I was not implementing the copy constructor properly.
Actually, in my post "Copy Constructor" I wrote:

For the List type, for example, the following approach would work:

class Customer  
{
private List names;

// Copy constructor.
public Customer(Customer previousCustomer)
{
names = new List(previousCustomer.names.ToArray());
}

...
}

This is not true for the list of reference type objects.

The workaround I use now is to implement a copy constructor in the reference type and create a copy of the list in the following manner:

class Customer  
{
private List customerIDs;

// Copy constructor.
public Customer(Customer previousCustomer)
{
customerIDs = new List();
foreach(ID id in previousCustomer.customerIDs)
{
customerIDs.Add(new ID(id));
}
}

...
}

The syntax could be a lot more elegant in 3.5, but this application uses the 2.0 framework.

by . Also posted on my website

No comments: