0

Pardon me if its a very foolish question. But I want to know why this is happening.

My code is

    static void Main(string[] args)
        {
            List<int> lst = new List<int>();
            for (int i = 0; i< 10; i++)
            {
                lst.Add(i);
            }

            List<int> lstRet = lst;
            List<int> lstRet2 = lstReturn(lstRet);
         }

        static List<int> lstReturn(List<int> lst)
        {
            List<int> NewList = lst;
            NewList.Remove(3);
            NewList.Remove(6);
            NewList.Remove(9);

            return NewList;
        }

The problem is after the method lstReturn(lstRet); is getting called, both the list Values values are same, as if lst and lstRet2 both are identical List.

Why it is like that. Can anybody please explain? Is only one copy of List is created, if yes, why?

I am again saying if its a duplicate, pardon me, I searched but didn't get any satisfactory answer.

Thanks

Edit: The question was not a duplicate, the solution lies elsewhere, may be the fundamental knowledge is same. Instead passing the same list lst to lstRet, if its like

List<int> lstRet = New List<int>(lst)

this solved the problem, Thanks to all of you for such a quick response.

Debhere
  • 1,055
  • 2
  • 19
  • 41

2 Answers2

3

The problem is with this line:

List<int> lstRet = lst;

It does not do what you want it to do - instead of copying the list, it copies the reference. You have only one list, from which the items get removed.

If you wish to make a copy, replace the line above with

List<int> lstRet = new List<int>(lst);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

They are the same list. You are assigning the return value of lstReturn to the variable lstRet2:

List<int> lstRet2 = lstReturn(lstRet);

and the function lstReturn returns the list that was passed in:

static List<int> lstReturn(List<int> lst)
    {
        List<int> NewList = lst; // NewList now is the list that was passed in

        // snip...

        return NewList;
    }
Chris Shain
  • 50,833
  • 6
  • 93
  • 125