Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass List to method without modifying original list

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
    }
}
like image 203
Paligulus Avatar asked Oct 10 '11 12:10

Paligulus


4 Answers

duplicate the list:

_myLocalList = new List<int>(_myList);

and perform the operations on the local list.

like image 59
Andreas Avatar answered Nov 17 '22 21:11

Andreas


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()) .

like image 44
Yahia Avatar answered Nov 17 '22 21:11

Yahia


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);
}
like image 3
Ilian Avatar answered Nov 17 '22 21:11

Ilian


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();
        }
}
like image 1
Saint Avatar answered Nov 17 '22 21:11

Saint