2

Consider this bit of code:

class X
{
     int _value;
     public object Value { get { return _value; } set { _value = Convert.ToInt32(value); } }
}

X x = new X();
object y = x.Value = 2.3;

To me it looks like y == 2.0 because that is the return value of x.Value, but it turns out that it is y == 2.3, even though x.Value == 2.

Why?

satnhak
  • 9,407
  • 5
  • 63
  • 81

4 Answers4

2

The line

object y = x.Value = 2.3;

is equivalent to

object y = 2.3;
x.Value = 2.3;

so, you will get result

y = 2.3
x.Value = 2

UPDATE

Some additional information after research of IL code:

Well, we have float value 2.3. The y and x.Value expects object type. In this case:

  • compiller declares a new variable let's call it V (object V).
  • push onto the stack float value 2.3
  • boxing this value to object
  • duplicates the value on the top of the stack. So, we will have 2 the same boxed values in stack (#1, #2).
  • pop #2 and assign it to V
  • assign x.Value = V (inside property value will be converted to int)
  • pop #1 and assign it to V
  • assign y = V

As a result we have something like this:

object V = (object)2.3;
x.Value = V;
y = V;
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • 1
    That's not true. According to the C# standard, `a = b = c;` is equivalent to `a = (b = c);`, because the assignment operators are right-associative. See section 7.17 of the standard. Although the standard seems a little flaky in this area... – Matthew Watson Jan 26 '17 at 10:21
2

I would guess that it's just asigning the values at the same time, not one after another.

In other words when you write

object y = x.Value = 2.3;

It is interpreted as

x.Value = 2.3; 
object y = 2.3;
yan yankelevich
  • 885
  • 11
  • 25
2

The return value of this piece of code:

x.Value = 2.3

is not x.Value. The getter is not run. The assignment operator returns the value to be assigned so that multiple assignment is possible.

The order of execution goes like this:

First, 2.3 is assigned to X.value. We don't care what the setter does with it, the statement (X.value = 2.3) returns the value 2.3

Second the returned statement from (X.value = 2.3) gets assigned to y

This concept is what makes multiple assignment look like two independent assignments:

X.value = 2.3
object y = 2.3
dimlucas
  • 5,040
  • 7
  • 37
  • 54
1

The assignment operator assigns the value of the right-hand operand to the variable on the left, and returns the assigned value. It does not fetch the new value of the variable or property.

Tommy Carlier
  • 7,951
  • 3
  • 26
  • 43