0

I have the following object being created:

var i = 0;
var foo = new Foo();
foo.A = ++i;
foo.B = ++i;
foo.C = ++i;

Assert(foo.A == 1);
Assert(foo.B == 2);
Assert(foo.C == 3);

The same object can we written using an object initializer:

var i = 0;
var foo = new Foo
{
    A = ++i,
    B = ++i,
    C = ++i
}

Assert(foo.A == 1);
Assert(foo.B == 2);
Assert(foo.C == 3);

Is the order that the properties are set guaranteed in the case of the object initializer?

Cœur
  • 37,241
  • 25
  • 195
  • 267
BanksySan
  • 27,362
  • 33
  • 117
  • 216
  • have you checked running it yourself? – Ehsan Sajjad Sep 04 '18 at 11:29
  • 1
    I think you mean: `var foo = new Foo {A = ++i, .. etc` – Stefan Sep 04 '18 at 11:29
  • 1
    @EhsanSajjad: I think running once would not guarantee it. – Stefan Sep 04 '18 at 11:29
  • 1
    @EhsanSajjad Running it would confirm the current implementation on the specific framework I'm using, it wouldn't confirm that it's a documented feature. – BanksySan Sep 04 '18 at 11:31
  • 1
    The *compiler* generates the *first* snippet when it sees the second one. Compilers *can* reorder statements if it's safe to do so. In this case though I'd expect the compiler to recognize the dependency and preserve the order – Panagiotis Kanavos Sep 04 '18 at 11:31
  • @PanagiotisKanavos the compiler optimizations are less than perfect. – BanksySan Sep 04 '18 at 11:37
  • Quote from the referenced question's answer: _I would also be very wary of actually writing code which depends on this..._ – BanksySan Sep 04 '18 at 11:40
  • @BaksySan in this case the compiler rewrites the code so it's *not* sensitive to reordering. Check [this snippet](https://sharplab.io/#v2:CYLg1APgAgDABFAjAbgLACgoGYECY4BiA9kXAN5wZzUI4CWAdgC5wCCa6NtcjLAQhy7YezOAGEOAXwwZhUfGPJUacgCxwAsgAoAlEs5caANwCGAJx5wAvHBiDD1UxYBmJa3AYBTAO6ESyhzIAh2pWdzAwOgAaYL5wyJiDakUbCLoMSXtqYOl0SSA) in SharpLab. The generated code is `num = (foo.C = (foo.B = (foo.A = num + 1) + 1) + 1);` `i` isn't modified until the end – Panagiotis Kanavos Sep 04 '18 at 11:53
  • @PanagiotisKanavos Good example, thanks. Intresting that it has the `num = ` at the front, there's no use of `num` ofter the assignments. – BanksySan Sep 04 '18 at 12:12

0 Answers0