In C#, if you have a struct like so:
struct Counter
{
private int _count;
public int Value
{
get { return _count; }
}
public int Increment()
{
return ++_count;
}
}
And you have a program like so:
static readonly Counter counter = new Counter();
static void Main()
{
// print the new value from the increment function
Console.WriteLine(counter.Increment());
// print off the value stored in the item
Console.WriteLine(counter.Value);
}
The output of the program will be:
1
0
This seems completely wrong. I would either expect the output to be two 1s (as it is if Counter is a class or if struct Counter : ICounter and counter is an ICounter) or be a compilation error. I realize that detecting this at compilation time is a rather difficult matter, but this behavior seems to violate logic.
Is there a reason for this behavior beyond implementation difficulty?