Clone in Constructor

C

csharpdummy

I would like to add a clone method in a constructor.
I tried the following, but it doesn't work.

public test(MyClass A)
{
this=A.Clone();
}
Is there a way to do this?
How would that look like for a base vs. derived class?

Thanks
 
R

Registered User

I would like to add a clone method in a constructor.
I tried the following, but it doesn't work.

public test(MyClass A)
{
this=A.Clone();
}
Is there a way to do this?
Yes but not like that. Use an overloaded constructor to return a shallow copy of
instance passed as the argument.

public class MyClass
{
public string S {get;set;}
public bool B {get;set;}
...
public MyClass(){}
public MyClass(MyClass a)
{
this.S = a.S;
this.B = a.B;
...
}
...
}
How would that look like for a base vs. derived class?
Derive a type from MyClass and work from there to answer this question.

regards
A.G.
 
C

CSharpDummy

Yes but not like that. Use an overloaded constructor to return a shallow copy of
instance passed as the argument.

public class MyClass
{
public string S {get;set;}
public bool B {get;set;}
...
public MyClass(){}
public MyClass(MyClass a)
{
this.S = a.S;
this.B = a.B;
...
}
...
}
Derive a type from MyClass and work from there to answer this question.

regards
A.G.

This one I knew - I was hoping there was a more elegant solution.
 
J

Jeff Johnson

This one I knew - I was hoping there was a more elegant solution.

So do you want to do this:

MyClass A = new MyClass();

MyClass B = new MyClass(A);

?

If so, why do you consider that better than

MyClass A = new MyClass();

MyClass B = (MyClass)A.Clone();

?
 
A

Arne Vajhøj

So do you want to do this:

MyClass A = new MyClass();

MyClass B = new MyClass(A);

?

If so, why do you consider that better than

MyClass A = new MyClass();

MyClass B = (MyClass)A.Clone();

?

That would be the C# way.

The copy constructor is most likely a C++ism.

Arne
 

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