@sparked said:
A nice little pitfall for the unaware: I'm not certain if this a compiler bug or a WTF in the C# specs. Assume the following class:
class Class1
{
private int i = 0;
public int pi
{
set
{
i = value;
}
get
{
return(i);
}
}
}
Now do this:
Class1 c = new Class1();
++c.pi;
After the increment, class.pi will equal.... zero. Stepping through in the VS debugger you'll see it enter the get block, return it, and then drop the value on the floor and ignore the implicit assignment. However:
c.pi += 1;
And class.pi will equal one.
To understand why this happens, you need to understand how properties in .NET really work.
In many ways, they appear to be public fields (member variables) on a class. However, because they can do all sorts of extra work behind they scenes, they are really functions that look like fields.
Another way of looking at the first case is:
Class1 c = new Class1();
++c.get_pi();
Here, you can see that by accessing a property, you're really calling a method. The ++ then increments the value returned by the method. However, as you're not using that value, the compiler can optimize away the increment operation.
Now for the second example. It's common knowledge that this:
c.pi += 1;
expands to this:
c.pi = c.pi + 1;
Looking at properties as functions again, it becomes this:
c.set_pi( c.get_pi() + 1 );
which is why it works.
Some of the other posters have mentioned that this works fine in VS.NET 2005 (.NET 2.0). My guess is that people complained to Microsoft about properties not working the same as fields, even though they appear the same when looking at the code.