So, the comparison would be between:
MyClass foo = new MyClass();
foo.Property1 = 4;
foo.Property2 = "garfield";
and
MyClass foo = new MyClass { Property1 = 4, Property2 = "garfield" };
Is it syntactic sugar, or is there actually some kind of performance gain (however minute it’s likely to be?)
It’s actually potentially very, very slightly slower to use an object initializer than to call a constructor and then assign the properties, as it has one extra assignment:
vs
The properties are all assigned before the reference is assigned to the variable. This difference is a visible one if it’s reusing a variable:
The output shows that in the second line of
Main, whenSecondis being set (afterFirst), the value ofshared.Firstis still “First 1” – i.e.sharedhasn’t been assigned the new value yet.As Marc says though, you’ll almost certainly never actually spot a difference.
Anonymous types are guaranteed to use a constructor – the form is given in section 7.5.10.6 of the C# 3 language specification.