I am looking to find a good way to skip copy constructor approach in C# and looking for a way to do same thing with assignment in code below:
class Person
{
string Name;
int Age;
public Person() { }
//public Person(Person p)//copy contructor
//{
// this.Name = p.Name;
// this.Age = p.Age;
//}
public Person(string name ,int age)
{
this.Name = name;
this.Age = age;
}
public void Set(string name,int age)
{
this.Name = name;
this.Age = age;
}
public void Get()
{
Console.WriteLine("{0} {1}",Name,Age);
}
};
Person person= new Person("Arif",40);
person.Get();
//Person person2 = new Person(person);//skip copy
Person person2 = new Person();
person2 = person;//use assignment
person2.Get();
person.Set("Mahmood",44);
person.Get();
person2.Get();
Output I see in case of copy when copy constructor is implemented is desired one given below
Arif 40
Arif 40
Mahmood 44
Arif 40
But output which I see for assignment is wrong one given below
Arif 40
Arif 40
Mahmood 44
Mahmood 44
How to get right output?
If we go solely by the example you provided, you need Person to be a 'structure'. They are assigned by copying a value rather than refference.
You cannot override the operator "=" in C# See here in MSDN
=, ., ?:, ??, ->, =>, f(x), as, checked, unchecked, default, delegate, is, new, sizeof, typeof =======> These operators cannot be overloaded
Moreover, assignments that deny the normal behaviour are confusing
person1 = person2; //Your Person class
county1 = country2; // Some other class
Both are instances of classes (Person & Country) and therefore referenced. Why does Person behave other than Country?!?
The copy constructor is the option to go here if you are using classes. A way to use the assignment operator is to use non-referenced types like primitives or a struct. However, a struct should not have functions! That's what classes are for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.