noobie: copy data in a constructor

C

Christoph Boget

Let's say I have the following class:

Class MyClass {
int prop1;
string prop2;

public MyClass() {
}

public MyClass(MyClass myClass) {
}
}

Is there an easier way of copying the data from the
myClass object passed to the second constructor
detailed above than the following:

public MyClass(MyClass myClass) {
prop1 = myClass.prop1;
prop2 = myClass.prop2;
}

My gut's telling me that there has to be an easier way,
especially because there are some classes that have a
large number of properties. I've looked at the

MemberwiseClone()

method but I don't see how I can use it within the
constructor because you can't assign the variable 'this'
to anything as it is read-only.

I'm just hoping someone can point me in the right direction
so I can read up on how to do this on my own. I'm just
not sure where to be searching as all the searches I've done
thus far have come up with nada.

thnx,
Christoph
 
J

Jon Skeet [C# MVP]

Christoph Boget said:
Let's say I have the following class:

Class MyClass {
int prop1;
string prop2;

public MyClass() {
}

public MyClass(MyClass myClass) {
}
}

Is there an easier way of copying the data from the
myClass object passed to the second constructor
detailed above than the following:

public MyClass(MyClass myClass) {
prop1 = myClass.prop1;
prop2 = myClass.prop2;
}

My gut's telling me that there has to be an easier way,
especially because there are some classes that have a
large number of properties. I've looked at the

MemberwiseClone()

method but I don't see how I can use it within the
constructor because you can't assign the variable 'this'
to anything as it is read-only.

I'm just hoping someone can point me in the right direction
so I can read up on how to do this on my own. I'm just
not sure where to be searching as all the searches I've done
thus far have come up with nada.

Instead of using MemberwiseClone in a constructor, you could use it in
a factory method. (Or you could implement ICloneable, for instance.)

I very rarely have to write this kind of copy constructor, however -
are you sure you really need it?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top