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);
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.
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
What you are trying to do can be achieved using 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();
You can't assign this
in a class type. The best way is probably to create another constructor and call that:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With