Create objects without reference C#

Asked

Viewed 1,833 times

6

My question is, I have two instance of the class Parents, faths1 and fathers2, I created the 3 instance of the class Parents called fathers3 and said that it will be equal to instance fathers2, until everything ok.

But my problem is that when I change the name of the parent object 2, it is also changed in the parent object3, which I can do not make one object not refer 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";
    }        
}
  • I think you seek to copy the object of pais2 (for example, create a new object and copy the value of the members). If C# equals C++, then that’s very easy... just do it, I guess: { Pais pais3_v = pais2; Pais& pais3 = pais_v; } (obviously would need to update members referencing/pointing values)

  • @Matheus, I honestly didn’t understand what you said.

  • For example, Hummm: Pais pais3 = new Pais(); pais3.Nome = pais2.Nome;. There must already be some function for that in C#.

  • 1

    @Matheus C# is not equal to C++. See my answer.

  • 1

    Related: https://answall.com/questions/12048/clonar-objetos-de-classe-usando-icloneable

2 answers

8


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.

So for all practical purposes both pais3 how much pais2 are effectively pointing to the same memory point.

What you are wanting may be better exposed this way:

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

One possibility is cloning, which is divided into shallow copies (Shallow copy) and deep (deep copy). The difference is that the former maintains references to the same objects pointed out by the properties of the cloned object; the latter also tries to clone the referenced objects.

The following example demonstrates the creation of a blank 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);
        }
    }
}

Utilizing:

Pais pais3 = pais2.DeepClone();

Source: https://stackoverflow.com/a/1213649/1845714

  • could explain me what the difference of the copy Raza for the deep copy?

  • 1

    @Nicolabogar He already explains in the answer. It’s like, if you have pais2.ref and pais2.ref reference to an object, then pais3.ref will receive a new object equal to pais2.ref (the same recursively occurs in members).

7

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. So if you move the object through one variable, the other variable sees the change because it’s the same object, you didn’t create another new one.

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

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

If you are going to do this often it pays to create a constructor that receives an object Pais as argument and the constructor itself takes charge of 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’s not always easy to make it work properly. Read a question about clone.

Also. Another example.

To cloning by serialization may be solution in some cases.

Another solution is to do the Pais be a guy by value, there is no problem. But it is not always adequate. The change in semantics can make certain uses impossible. From the text showing what you want it seems you can’t do this.

  • I created a method as he explained using Memorystream and Binaryformatter and it worked, but my question is this, what difference does it make if I do this cloning by this method or using Memberwiseclone. I couldn’t understand that explanation. (The difference is that the former maintains references to the same objects pointed out by the properties of the cloned object; the latter also tries to clone the referenced objects.)

  • @Nicolabogar working out and being right are different things. Then I’ll improve the answer, but I don’t know if I would do it. Read the links what did I pass? There’s this one too: https://answall.com/q/138003/101, then I put something on it

  • I read the articles yes, and it really worked, it was exactly what I needed, to clone the object without having any reference. I was just wondering when to use the serialization or the Memberwiseclone mode, that’s all, but thanks for the info. Gave to solve my problem in question that is to obtain a copy of the object without being by reference.

  • Interesting solution to do Pais a Struct.

  • I’m going to say it again, to succeed and to be right are completely different things. @Matheus but in this case it doesn’t seem to be suitable, at least in real object. Of course it might be, if you only have a name and nothing else, it’s quite appropriate, is that I think it won’t be just this.

  • @bigown Yes, for example, when the instance has members that reference objects (I hope I’m right about C#). But that should occupy more memory depending.

  • 2

    @Matheus is not quite that, see https://answall.com/q/16181/101 and has the link in my reply above. Structures take up less memory if you do it right, where it’s right

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.