0

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();

        }
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    Try `List localNumbers = numbers.ToList();` so that you create a copy instead of assigning and mutating the same list. – juharr Sep 24 '21 at 20:01

1 Answers1

-1

By calling List<int> localNumbers = numbers; you're assigning both variables to point to the same object, so any changes made through one of them are visible through the other. One way to create a copy of a list is by using Linq's ToList:

List<int> localNumbers = numbers.ToList();
Mureinik
  • 297,002
  • 52
  • 306
  • 350