I have two same types of lists: list1 and list2. and the program has a structure as follows. each i loop the list1 size changes. I want to use list2 to keep data in list1 before calling func5() if condition1 is satisfied. how can I do this? Thanks
The code structure:
main()
{
List<class>List1 = new List<class> ();
loadup List1;
List<class>List2 = new List<class> ();
for int i=1; i<=5;i++
{
...
{
list2.Clear();
for (int i = 0; i < list1.Count; ++i)
{
list2.Add(list1[i]);
}
return true;
}
and change func (ref list1) to func(ref list1, ref list2)
and in the body of func(ref list1, ref list2)
before call func5(ref list1), the following code is added:
so list2 should keep list1 data before calling func5(). since func5(ref list) updates list1, after calling func5(ref list1), list1 and list2 are different. However, I found list2 changed too after calling func5(ref list1). i.e., list2 = list1. what's wrong in my code?
It's because C# has value types (structs) and reference types (classes).
Value types (like bool, float, double, int, long...) will always be passed around by value (a copy is made), while reference types are passed by reference (the variable refers to the original object).
This means that what Access_Denied suggested would work with value types - the two arrays would contain two distinct sets of values. But with reference types, as in your case, that code results in a shallow copy (two array objects referencing the same set of elements). Note that when mutating the elements, both arrays are affected, but when replacing/removing an element in one array, then nothing changes in the other.
So you need to modify your class to provide a method that enables it to copy itself, or provide a constructor that makes a deep copy of an existing object.
Say you added a Copy() method. You would then create the second list like this: list2.Add(list1[i].Copy());
Last edited by TheGreatCthulhu; April 24th, 2012 at 08:15 PM.
Be careful with Clone(): always read the MSDN documentation for the specific class you're working with - clone can be implemented as shallow copy for some types (for example, calling Clone() on arrays types creates a shallow copy).
Be careful with Clone(): always read the MSDN documentation for the specific class you're working with - clone can be implemented as shallow copy for some types (for example, calling Clone() on arrays types creates a shallow copy).
Thanks for the reminding. I will be careful using Clone(). the reason I use the Clone() is because there is no Copy() available for my case.
Bookmarks