Pass List to method without modifying original list
19,082
Solution 1
duplicate the list:
_myLocalList = new List<int>(_myList);
and perform the operations on the local list.
Solution 2
Use AsReadOnly
for this:
class CopyTest1
{
List<int> _myList = new List<int>();
public CopyTest1(IList<int> l)
{
foreach (int num in l)
{
_myList.Add(num);
}
_myList.RemoveAt(0); // no effect on original List
}
}
And call it via CopyTest1(yourList.AsReadOnly())
.
Solution 3
There is another way. You can use the copy constructor of List<T>
:
List<int> _myList;
public CopyTest1(List<int> l)
{
_myList = new List<int>(l);
}
Solution 4
Clone objects in the list to other list and work on this copy
static class Extensions
{
public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable
{
return listToClone.Select(item => (T)item.Clone()).ToList();
}
}
Comments
-
Paligulus almost 2 years
Is this the only way of passing a List to a method and editing that List, without modifying the original List?
class CopyTest1 { List<int> _myList = new List<int>(); public CopyTest1(List<int> l) { foreach (int num in l) { _myList.Add(num); } _myList.RemoveAt(0); // no effect on original List } }
-
Paligulus over 12 yearsIf the callers forgets to create a copy then they will get unexpected behaviour - I would prefer for the class\method to handle it
-
Simon Stender Boisen over 12 yearsThat depends what the purpose of the class is, is it do modify a collection or to create a copy of a collection and modify it? The example is a bit contrived and I don't think it's obvious exactly what you wanted.
-
newacct over 12 yearsand in any case it is not necessary to pass it as
ref
to alter the original list --ref
allows you to change the reference in the caller's scope to point to another object, something that is highly unlikely to be useful