Reputation: 778
I know this Questions is asked and has answer already here: C# how to assign List<T> without being a reference?
but as @Dev said it is still being referenced. my "name_list1
" is static and then I am coping like:
name_list2 = new List<string>(name_list1);
as answered in above link. i have tried all possible solution founded from stackoverflow like:
using - AddRange
, ToList
, ToArray
and all. but still it is creating ref only to name_list1
. as I am changing object value in name_list2
it is affected in name_list1
too.
I needed to ask this Question again as I am not able to comment on others question due to <50 reputation :P :(
Upvotes: 0
Views: 475
Reputation: 778
To Simply solve this I have added each value of object item manually. As i also tried to iterate through each object to add it in list, and that's didn't work. So For me Simple solution is to write constructor of list item object, which has one argument which accept object type of itself and add all value manually. I will do more on some time to solve this in better way. Thanks all for help :)
And Also we can use:
public static T DeepCopy<T>(T item)
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, item);
stream.Seek(0, SeekOrigin.Begin);
T result = (T)formatter.Deserialize(stream);
stream.Close();
return result;
}
Upvotes: 1
Reputation: 30698
You need to iterate through first list, and clone all the objects, and then add these to list2.
Otherwise, even though list object are different, the items they refer to are still same so any change made to list items, will be reflected through other list.
Refer to this SO answer for how to clone. Deep cloning objects.
Also, One concept to understand is that, when you create another list and use AddRange, both list objects are different.
Changes to one list are not reflected in other list. These changes include adding list item, removing list item, ordering list item.
These collection level changes are different from changes in individual list items, which are reflected as individual list items are still the same in both list (unless they are cloned prior to adding to the list).
Upvotes: 3