Paligulus
Paligulus

Reputation: 493

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
    }
}

Upvotes: 10

Views: 23760

Answers (6)

dougajmcdonald
dougajmcdonald

Reputation: 20057

You can pass an object by reference doing the following:

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

EDIT: The question has now been clarified, the OP was after a way not to alter the original list.

Upvotes: -1

Simon Stender Boisen
Simon Stender Boisen

Reputation: 3431

When you pass a list to a method you pass a pointer to said list, that's why your changing the 'original' list when you modify it inside your method. If you instead want to modify a copy of the list you just need to make one. In the code that calls CopyTest1 you can create a new list based on your 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
    }
}

Upvotes: 0

Yahia
Yahia

Reputation: 70369

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

Upvotes: 6

Ilian
Ilian

Reputation: 5355

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);
}

Upvotes: 3

Saint
Saint

Reputation: 5469

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();
        }
}

Upvotes: 1

Andreas
Andreas

Reputation: 6475

duplicate the list:

_myLocalList = new List<int>(_myList);

and perform the operations on the local list.

Upvotes: 19

Related Questions