C # Returned object from array leaves pointer to Array element

I have List<T>, and I do the following:

var myObj = List[2];  //Return object at position 2
myObj.Name = "fred";  //If you look at List[2] its name has changed to fred

I tried the following, but it still updates the item in the list

var newObj = new MyObj();
var myObj = List[2];  //Return object at position 2
newObj = myObj;
newObj.Name = "fred";  //If you look at List[2] its name has still changed to fred

How can I avoid this pointer so that I can update properties without updating it in the list?

+3
source share
5 answers

Great comments, thanks, but this is what I implemented:

public MyObj Clone()
    {
        BinaryFormatter bFormatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        bFormatter.Serialize(stream, this);
        stream.Seek(0, SeekOrigin.Begin);
        MyObj newObj = (MyObj)bFormatter.Deserialize(stream);
        return newObj;
    }
+1
source

You can create an ICloneable with MemberwiseClone , and then:

var myObj = List[2];
var newObj = myObj.Clone();
newObj.Name = "fred";

UPDATE:

, ICloneable, , . Clone .

+3

- , . :

MyObj a = new MyObj();
MyObj b = a;
a.Name = "Test";
Console.WriteLine(b.Name); // Will print "Test"

- ( , ), .

.

, , . -, .

+2

? , , ?

.

var newObj = new MyObj(List[2]);
newObj.Name = "fred";

, , . , , -

var newObj = new MyObj(List[2],"fred");

.

- , .

, , -, " " ( IClonable ), , , newObj? ? ? , /, ?

+1

. # " ", , , ( "" ) . , , . , , . , , . , ICloneable, , "" . , , - " ". , ? " " . , " !"

+1
source

Source: https://habr.com/ru/post/1728275/


All Articles