Recently, I found a post on Internet asking this question, I tried to figure out but not sure.
I guess the problem is related with Boxing and Unboxing:
public readonly object counter = new Counter();
This line boxs a Counter onto heap, and counter refers to it.
((Counter)riddle.counter)
This line unboxs the Counter from heap.
Every time data it unboxs from heap is same as origin. Therefore, Line A doesn't affect Line B because they both retrieve from heap and are two different instances of Counter.
Is that right? Sorry for my poor English.
public void WantToKnow()
{
var riddle = new Riddle();
((Counter)riddle.counter).Increment(); // Line A
Console.WriteLine(((Counter)riddle.counter).Count); // Line B
// Why the output is 0?///////////////////
}
struct Counter
{
private int x;
public void Increment() { this.x++; }
public int Count { get { return this.x; } }
}
class Riddle
{
public readonly object counter = new Counter();
}