Good! I have the following code:
public class Persona
{
// ...
public string Apellido;
}
public class Program
{
public static void Main()
{
Persona A = new Persona(); A.Apellido = "Mendez";
Persona B = A; // El apellido debe ser Mendez.
//Pero...
Console.WriteLine("Apellido de A: " + A.Apellido); // Mendez ahora.
A.Apellido = "Castillo"; // Si por algún "error" debo cambiarlo.
Console.WriteLine("Nuevo Apellido de A: " + A.Apellido); // Castillo ahora.
Console.WriteLine("Apellido de B: " + B.Apellido); // Castillo igual.
}
}
Why is the field Apellido
in variable B affected by the change in variable A and vice versa?
What happens is that class variables only hold a reference to the instance (similar to pointers) so you have a single instance that you can access through two different variables, it goes something like this:
When you assign it to another variable it does not mean that a new instance is created and the values of the fields are copied.
It is affected because objects are assigned by reference. When you assign like this
the instance of B is a pointer to that of A, any change you make to either variable will affect the other.
To avoid this problem you must create a different instance or create a clone.
How to: Write a Copy Constructor (C# Programming Guide)
analyze in the example how it defines a constructor to create a new copy from an existing one.
You could also analyze the use of the
Object.MemberwiseClone (Method)
you could create a copy in another instance.
Because you are using the same instance of A for B;
When changing some property in A, the changes are reflected in B.
To avoid problems you can create another instance of the class
Persona()
for variable B:Or create a clone, you can create a method to copy an object, this is an example:
About Copy Constructor (English)