Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Returning object from Array leaves pointer to Array item

I have a 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 remaining so I can update properties without it updating it in the list?

like image 352
Jon Avatar asked Mar 25 '26 15:03

Jon


1 Answers

You could make your object implement the ICloneable interface using the MemberwiseClone method and then:

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

UPDATE:

As pointed out in the comments section it is not recommended to implement the ICloneable interface as it does not specify if it will perform a shallow or deep clone. Just add a Clone method to your class.

like image 171
Darin Dimitrov Avatar answered Mar 27 '26 06:03

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!