C# copy constructor

.net, c#, constructor

Solution

You can't assign the class itself - a constructor of that form will typically copy members of the other class:

public MyClass(MyClass s)
{
    this.s1 = s.s1;
    this.s2 = s.s2;
    this.v1 = s.v1;
}

That gives you a "copy" by value of the items in your other class. If you want to have the reference shared, you can't do that, but you wouldn't need a constructor - assigning the variables works fine for that:

var orig = new MyClass();
var referencedCopy = orig; // Just assign the reference

Problem

I apologize for asking something that is probably too basic for C# folks. I'm mostly doing my coding in C++. So if I want to write an assignment constructor for my class, how do I do that? I have this so far, but it doesn't seem to compile: ``` public class MyClass { public string s1; public string s2; public int v1; public MyClass() { s1 = ""; s2 = ""; v1 = 0; } public MyClass(MyClass s) { this = s; //Error on this line } } MyClass a = new MyClass(); MyClass b = new MyClass(a); ```

Original source

Related problems