Shallow copies of objects - or - Copy constructors

  • Thread starter Thread starter Adam W Root
  • Start date Start date
A

Adam W Root

So I have a Product and an extending class ProductLine. I want to create a
new ProductLine from a Product.

I wrote this in a constructor:

public Product(Product p)
{
foreach (System.Reflection.FieldInfo info in
p.GetType().GetFields(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic))
info.SetValue(this, info.GetValue(p));
}

First, is this a huge performance hit? I've heard rumors about reflection
being the devil for performance, but as I understand it, reflection is a
central technology for the framework, and therefore there is lots of it
going on, so why would a bit more hurt anything?

Second, did I solve a problem that has already been solved? I know there is
a Memberwise clone, but this is invalid (assigning to this):

public Product(Product p)
{
this = (Product)p.MemberwiseClone();
}

Also, ICloneable's Clone method has a similar downfall.

Any feedback would be great. I've posted on this before with no response, so
I'd like to see even a "Yeah, I think that works" type of response.

Thanks everybody.

Adam
 
Adam W Root said:
So I have a Product and an extending class ProductLine. I want to create a
new ProductLine from a Product.

I wrote this in a constructor:

public Product(Product p)
{
foreach (System.Reflection.FieldInfo info in
p.GetType().GetFields(System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic))
info.SetValue(this, info.GetValue(p));
}

First, is this a huge performance hit? I've heard rumors about reflection
being the devil for performance, but as I understand it, reflection is a
central technology for the framework, and therefore there is lots of it
going on, so why would a bit more hurt anything?

Second, did I solve a problem that has already been solved? I know there
is
a Memberwise clone, but this is invalid (assigning to this):

Yes, this is the point of Memberwise Clone. I would recommend *not* using
copy constructors and using ICloneable for various reasons, not the least of
which polymorphic behaviour. Copy constructors require you to know the
*exact* type of the object when you intend to clone it.
public Product(Product p)
{
this = (Product)p.MemberwiseClone();
}

Also, ICloneable's Clone method has a similar downfall.

The proper way to do things would be something like:

public object Clone()
{
MyObject x = this.MemberwiseClone();
return x;
}

while doing any particulars you need to do to x to handle other
cloning(references type fields are shallow copied(only the reference is
copied) in MemberwiseClone()).
 
Back
Top