开发者

what value will have property of my object?

Hi in my opinion property of my object shouold be 2, but after this code, is still 1, why?

internal class Program
{
    private static void Main(string[] args)
    {
        MyClass value = new MyClass() { Property = 1 };

        value.Property = value.Property++;
        Console.WriteLine(value.Property);
       开发者_StackOverflow中文版 Console.ReadKey();
    }
}

internal class MyClass
{
    public int Property;
}

in my opinion this should value.Property = value.Property++; first put to value what is in value and the increment property of this object, why id doesn't work?


What this does is:

  1. Evaluate value.Property on the right hand side (result is 1) and remember the result
  2. Increment value.Property (now it's equal to 2)
  3. Assign the remembered result to value.Property (it's now again equal to 1!)

If you change Property to a property with an explicit getter and setter and put some debugging code inside the setter, you will see that it does indeed change values 1 -> 2 -> 1.

If you changed value.Property++ to ++value.Property, the first two steps would be reversed, so we 'd have:

  1. Increment value.Property (now it's equal to 2)
  2. Evaluate value.Property on the right hand side (it's still 2)
  3. Assign the result of step 2 to value.Property (it's still 2)

Of course, this is unnecessarily complicated and one could even say, wrong. If you want to increment Property, all you have to do is this:

++value.Property;


Because valueProperty++ is the same as the following:

int Increment(ref int value)
{
    var temp = value;
    value = value + 1;
    return temp;
}


value.Property = value.Property++;

Here value.Property++ means it assing 1 before incrementing.


Because the = operator is lower down the order of operator precedence than increment.

http://msdn.microsoft.com/en-us/library/6a71f45d.aspx <- shows al the operators and their order of precedence.

The increment gets evaluated first completely. then the returned value from the increment is put through the = operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜