-4

This is supposed to happen for the task that I'm currently doing, but I don't understand why this is taking place. When myCounter[2].Reset() is called it resets the values of both myCounters[0] and myCounters[2]. Why is this occuring

Program.cs

namespace CounterTest
{
   public class MainClass
    {
        private static void PrintCounters(Counter[] counters)
        {
            foreach ( Counter c in counters) 
            {
                Console.WriteLine("Name is: {0} Value is: {1}", c.Name, c.Value);
            }
        }
       public static void Main(string[] args)
        {
            Counter[] myCounters = new Counter[3];
            myCounters[0] = new Counter("Counter 1");
            myCounters[1] = new Counter("Counter 2");
            myCounters[2] = myCounters[0];

            for (int i=0; i<4 ; i++)
            {
                myCounters[0].Increment();
            }
            for (int i = 0; i < 9; i++)
            {
                myCounters[1].Increment();
            }
            MainClass.PrintCounters(myCounters);

            myCounters[2].Reset();

            MainClass.PrintCounters(myCounters);

        }
    }
}

Class1.cs

namespace CounterTest
{
    public class Counter
    {
        private int _count;
        public int Value
        {
            get
            {return _count;}
        }
        private string _name;
        public string Name
        {
            get {return _name; }
            set {_name = value; }
        }

        public Counter(string Name)
        {
            _name = Name;
            _count = 0;
        }

        public void Increment()
        { _count = _count + 1; }
        public void Reset()
        {_count = 0;}
    }
}

The output is:

Name is: Counter 1 Value is: 4

Name is: Counter 2 Value is: 9

Name is: Counter 1 Value is: 4

Name is: Counter 1 Value is: 0

Name is: Counter 2 Value is: 9

Name is: Counter 1 Value is: 0

Thank you for any help.

TKeys23
  • 23
  • 1
  • 4
  • 2
    Because `myCounters[2] = myCounters[0]`... – Patrick Hofman Aug 15 '19 at 12:20
  • I would understand it if ```myCounters[0] = myCounters[2]``` then I can see how they affect each other, but I don't understand how resseting the value of myCounter[2] changes [0] – TKeys23 Aug 15 '19 at 12:28

1 Answers1

7

Because of the code:

myCounters[2] = myCounters[0];

myCounters[2] is literally a reference to myCounters[0], not a copy. Modifying myCounters[2] will also affect myCounters[0].

Lukas
  • 498
  • 2
  • 12
  • I didn't know what a shallow copy was since i'm still new to c#. Thank you for you're help though – TKeys23 Aug 15 '19 at 12:37