Pass the list to the method without changing the original list

Is this the only way to pass a list to a method and edit that list without changing 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 } } 
+4
source share
6 answers

duplicate list:

 _myLocalList = new List<int>(_myList); 

and perform operations in the local list.

+10
source

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 name it through CopyTest1(yourList.AsReadOnly()) .

+3
source

Clone objects in the list to another list and work with 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(); } } 
+1
source

There is another way. You can use the List<T> copy constructor:

 List<int> _myList; public CopyTest1(List<int> l) { _myList = new List<int>(l); } 
+1
source

When you pass a list to a method that you pass to the pointer to the specified list, why do you change the "source" list when it changes inside your method. If you want to change a copy of the list, you just need to create it. In the code that CopyTest1 calls, you can create a new list based on the original list:

 public void CallsCopyTest1() { var originalList = new List<int>(); var newList = new List<int>(originalList); var copyTest = new CopyTest1(newList); //Modifies newList not originalList } 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 } } 
0
source

You can pass an object by reference by doing the following:

 public static void ReferenceMethod(ref List<T> myParam) { ... } 

EDIT: The question is now clarified, OP was after it did not change the original list.

-1
source

All Articles