Create objects without reference C #

6

My question is, I have two instance of the class Parents, pais1 and pais2, I created the 3rd instance of the class called pais3 and said that it will be the same as the pais2 instance, until everything is ok.

My problem is that when I change the name of the parent object 2, it is also changed in the parent object3, what can I do not one object not being related to the other?

public class Teste
{
    public Teste()
    {
        Pais pais1 = new Pais();
        pais1.Nome = "Pais 1";

        Pais pais2 = new Pais();
        pais2.Nome = "Pais 2";

        Pais pais3 = new Pais();
        pais3 = pais2;

        pais2.Nome = "Pais 1000";
    }        
}
    
asked by anonymous 14.06.2017 / 00:58

2 answers

7

Quick explanation of your code:

Pais pais3 = new Pais(); // Cria uma nova instância de pais(), 
                         //    e a referencia como pais3.

pais3 = pais2;           // pais3 recebe uma nova referência, e agora
                         //    aponta para o mesmo objeto que pais2;
                         //    o objeto criado na expressão anterior
                         //    não tem mais referências, será coletado
                         //    pelo Garbage Collector eventualmente
                         //    e descartado.

Thus, for all practical purposes both pais3 and pais2 are effectively pointing to the same point in memory.

What you're looking for may be best exposed this way:

  

An object whose properties have the same value as another object.

One of the possibilities is cloning, which divides between shallow copy ( shallow copy ) and deep deep copy copies. The difference is that the former holds references to the same objects pointed to by the properties of the cloned object; the second also tries to clone the referenced objects.

The following example demonstrates the creation of a shallow copy:

Pais pais3 = (Pais)pais2.MemberwiseClone();

The example below uses MemoryStream and BinaryFormatter to allow deep copies:

public static class ExtensionMethods
{
    // Deep clone
    public static T DeepClone<T>(this T a)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, a);
            stream.Position = 0;
            return (T) formatter.Deserialize(stream);
        }
    }
}

Usage:

Pais pais3 = pais2.DeepClone();

Source: link

    
14.06.2017 / 01:25
6

Read this .

In reference types, the assignment operator only copies the variable reference, in practice you do not have two objects but two variables that point to the same object. Then move the object through one variable, the other variable sees the change because it is the same object, you did not create another one.

The solution to this is to create a new object from scratch, since it seems that you want each one to be individual, have its own identity.

An easy way is to create the object in hand as you created the other objects, eventually using the previous one as a basis for picking up the values already used, but still creating a new object.

If you are going to do this often make up for a constructor that receives a Pais object as an argument and the constructor itself is responsible for reading the data of this object to create a new object. This is not always possible.

You can use a cloning technique inside the object. It is not always easy to make it work properly. Read a clone question .

Also . Another example .

cloning by serialization may be a solution in some cases.

Another solution is to make the % with% being one type per value , so there is no such problem. But it is not always appropriate. The change in semantics can make certain uses unfeasible. By the text showing what you want it looks like you can not do this.

    
14.06.2017 / 01:13