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.