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
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)– Klaider
@Matheus, I honestly didn’t understand what you said.
– Nicola Bogar
For example, Hummm:
Pais pais3 = new Pais(); pais3.Nome = pais2.Nome;
. There must already be some function for that in C#.– Klaider
@Matheus C# is not equal to C++. See my answer.
– Maniero
Related: https://answall.com/questions/12048/clonar-objetos-de-classe-usando-icloneable
– novic