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