How do I change my new list without changing the original list?

You need to clone your list in your method, because List<T> is a class, so it's reference-type and is passed by reference.

For example:

List<Item> SomeOperationFunction(List<Item> target)
{
  List<Item> tmp = target.ToList();
  tmp.RemoveAt(3);
  return tmp;
}

Or

List<Item> SomeOperationFunction(List<Item> target)
{
  List<Item> tmp = new List<Item>(target);
  tmp.RemoveAt(3);
  return tmp;
}

or

List<Item> SomeOperationFunction(List<Item> target)
{
  List<Item> tmp = new List<Item>();
  tmp.AddRange(target);
  tmp.RemoveAt(3);
  return tmp;
}

You need to make a copy of the list so that changes to the copy won't affect the original. The easiest way to do that is to use the ToList extension method in System.Linq.

var newList = SomeOperationFunction(target.ToList());

Build a new list first and operate on that, because List is a reference type, i.e. when you pass it in a function, you do not just pass the value but the actual object itself.

If you just assign target to mainList, both variables point to the same object, so you need to create a new List:

List<Item> target = new List<Item>(mainList);

void List<Item> SomeOperationFunction() makes no sense, because either you return nothing (void) or you return a List<T>. So either remove the return statement from your method or return a new List<Item>. In the latter case, I would rewrite this as:

List<Item> target = SomeOperationFunction(mainList);

List<Item> SomeOperationFunction(List<Item> target)
{
    var newList = new List<Item>(target);
    newList.RemoveAt(3);
    return newList;
}

Tags:

C#