I am somewhat confused trying to do the following and I hope you can help me.
I have a class with a series of strings:
public class Ejemplo{
private string nombre;
private string id;
private string descripcion;
...
}
What I need is to clone this object but keeping the reference of certain strings
to the original. For this I have a Clone()
method that returns a copy of the object:
public object Clone(){
Ejemplo ejemplo = new Ejemplo();
ejemplo.nombre = this.nombre;
ejemplo.id = this.id;
ejemplo.descripcion = this.descripcion;
...
return ejemplo;
}
And then there are other variables that if I initialize them as a new object since I want them to be independent (hence the copy). By doing it in this way I get the copy right, but by modifying the original object I can not get these changes to be replicated in the copy.
What I would want is that if I change the name or other strings
in the original object it will also change in the copy. Right now he does this to me:
Ejemplo ejemplo = new Ejemplo();
ejemplo.nombre = "Hola";
Ejemplo ejemplo2 = ejemplo.Clone();
Console.WriteLine(ejemplo.nombre); // Muestra "Hola"
Console.WriteLine(ejemplo2.nombre); // Muestra "Hola"
ejemplo.nombre = "Adios";
Console.WriteLine(ejemplo.nombre); // Muestra "Adios"
Console.WriteLine(ejemplo2.nombre); // Muestra "Hola"
And what I would like to achieve is this:
Ejemplo ejemplo = new Ejemplo();
ejemplo.nombre = "Hola";
Ejemplo ejemplo2 = ejemplo.Clone();
Console.WriteLine(ejemplo.nombre); // Muestra "Hola"
Console.WriteLine(ejemplo2.nombre); // Muestra "Hola"
ejemplo.nombre = "Adios";
Console.WriteLine(ejemplo.nombre); // Muestra "Adios"
Console.WriteLine(ejemplo2.nombre); // Muestra "Adios"
I tried to assign it with ejemplo.name = String.Intern(this.name);
but the same thing keeps happening to me.
Any idea how I could do this, what concept is failing me or is it possible to do it? Thanks in advance.