Sorry if the subject seems vague, I tried summing it up as best I can without knowing the exact terminology of what I'm trying to achieve.
Essentially I have a list and then I call a method
public List<int> myList;
void Start () {
myList = new List<int>();
myList.Add (1);
myList.Add (2);
doSomething(myList);
foreach (int i in myList){
print (i);
}
}
In my method I'd like to do this (for example)
public void doSomething (List<int> myPassedList)
{
int A = 5;
myPassList.Add (A);
//... And then some other cool code with this modified list
}
However, I dont want the original list changed, I want it exactly as it was. Essentially when I pass the list into the method I'd like a duplicate of the list, which is then made new each time the method is called.
I want to see the console print '1' then '2'
but it will print '1', '2' and '5'
Hopefully this all makes sense! Thanks very much in advance for any help
Jim
By default, C# does not allow you to choose whether to pass each argument by value or by reference. Value types are passed by value. Objects are not passed to methods; rather, references to objects are passed—the references themselves are passed by value.
A list can be accessed by an index, a for/foreach loop, and using LINQ queries. Indexes of a list start from zero. Pass an index in the square brackets to access individual list items, same as array. Use a foreach or for loop to iterate a List<T> collection.
C# List access elements. Elements of a list can be accessed using the index notation [] . The index is zero-based. using System; using System.
List
is a reference type so when you pass myPassedList
as an argument to doSomething
you are modifying the original list.
You have two options, either call ToList()
or create a new list, as an example:
public void doSomething (List<int> myPassedList)
{
List<int> newList = myPassedList.ToList();
int A = 5;
newList.Add(A);
//... And then some other cool code with this modified list
}
The original list myList
will then only return 1 and 2.
If you write a method that works with a list but will not modify that list, then you should document this by code with
public void doSomething ( IEnumerable<int> myPassedValues )
{
List<int> newList = myPassedValues.ToList();
int A = 5;
newList.Add(A);
//... And then some other cool code with this modified list
}
Now you and all others will know, just by reading the declaration that the passed list will not be modified in this method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With