Hello, I read on a couple of forums that it is impossible to overload this operator. How to solve this problem? '

{ public static void operator = (Person p, Person p1); }` 

Just if you use ArrayList.Colone (), then by changing the new collection I change the original one, how can this be avoided? Thank you for your attention, tell me where to dig.

  • What is your problem? Yes, assignment cannot be overloaded, so most likely your problem is solved differently. - VladD
  • 2
    in this case, inherit your Person class from the IClonable interface and implement the Clone method in your own way. This is exactly what it is intended for - rdorn pm
  • one
    Well, it is clear that in order for new Person(this) compiled, a Person must have a Person(Person other) constructor Person(Person other) . - VladD
  • one
    Well, I thought there is a standard element-by-element copy method of independent elements. I am just with the C ++ base, and I am often scolded that I will bicycles when I have a ready-made solution. - SkiF
  • one
    and also, instead of ArrayList, use better List <T> if the task allows - rdorn

1 answer 1

The assignment operator, like some others, cannot really be redefined (see MSDN ). But if you have access to the source code for the Person class, then to solve your problem, it is enough to inherit the Person class from the IClonable interface and implement this interface like this:

 public class Person : IClonable { // тут ваши поля и методы public object Clone() { var personClone = new Person(); //тут копируем в новую сущность нужные свойства return personClone; } } 

After that, you can easily copy elements, for example:

 Person p1 = new Person() { //присвоили значения полям } Person p2 = p1.Clone(); 

In this case, p2 will receive a new reference to its own Person object. True, you will have to manually copy the collection elementwise in a loop, since the Clone method implemented in standard collections makes incomplete copying and in the case of elements of the reference type, it copies links. But in this case, you can provide a static method in the Person class that receives the collection as input and returns a copy of it.