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.