C # Copy Constructor

I apologize for asking a question that is probably too important for C # people. I mainly do my c ++ coding.

So, if I want to write an assignment constructor for my class, how do I do this? I still have this, 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); 
+4
source share
4 answers

You cannot assign a class itself - the constructor of this form usually copies the members of another class:

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

This gives you a “copy” of the value of objects of another class. If you want the link to be split, you cannot do this, but you do not need a constructor. Assigning variables is great for this:

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

You cannot assign this to a class type. The best way, probably, is to create another constructor and call:

 public MyClass() : this(string.Empty, string.Empty, 0) { } public MyClass(MyClass s) : this(s.s1, s.s2, s.v1) { } private MyClass(string s1, string s2, int v1) { this.s1 = s1; this.s2 = s2; this.v1 = v1; } 
+1
source

What you are trying to do can be achieved with Clone

 public class MyClass : ICloneable { public string s1; public string s2; public int v1; public MyClass() { s1 = ""; s2 = ""; v1 = 0; } public Object Clone() { return this.MemberwiseClone(); } } 

consuming:

 MyClass a = new MyClass(); MyClass b = (MyClass)a.Clone(); 
+1
source

Is this not a smart decision?

 public myClass() { s1 = ""; s2 = ""; v1 = 0; } public myClass(String _s1, String _s2, Int _v1) { s1 = _s1; s2 = _s2; v1 = _v1; } 

then from your code

 myClass a = new myClass(); myClass b = new myClass(a.s1,a.s2,a.v1); 
+1
source

Source: https://habr.com/ru/post/1496023/


All Articles