I wanted to initialize my class with the list of ints for example:
{1,5,6,7,1,0}
and then modify them and get two fields, one with the same list of ints and the second with a modified list of ints. But as a result, I get two modified lists with values: {0,4,5,6,0,0}
. Can someone explain to me why this code acts like this?
MyClass
public class MyClass
{
public List<int> numbers { get; }
public List<int> diffrentNum { get; set; }
public MyClass(List<int> _numbers)
{
numbers = _numbers;
diffrentNum = GetNumbers();
}
private List<int> GetNumbers()
{
List<int> localNumbers = numbers;
for (int i=0;i<localNumbers.Count-1;i++)
{
if (localNumbers[i] > 0)
{
localNumbers[i]--;
}
}
return localNumbers;
}
}
Main
static void Main(string[] args)
{
List<int> someDate = new List<int>();
someDate.Add(1);
someDate.Add(5);
someDate.Add(6);
someDate.Add(7);
someDate.Add(1);
someDate.Add(0);
MyClass myclass= new MyClass(someDate);
Console.WriteLine(String.Join("", new List<int>(someDate).ConvertAll(i => i.ToString()).ToArray()));
Console.WriteLine(String.Join("", new List<int>(myclass.numbers).ConvertAll(i => i.ToString()).ToArray()));
Console.WriteLine(String.Join("", new List<int>(myclass.diffrentNum).ConvertAll(i => i.ToString()).ToArray()));
Console.ReadKey();
}