Is there a performance improvement if using an object initializer, or is it asthetic?
c#
Solution
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:
MyClass foo = new MyClass();
foo.Property1 = 4;
foo.Property2 = "garfield";
vs
MyClass tmp = new MyClass();
tmp.Property1 = 4;
tmp.Property2 = "garfield";
MyClass foo = tmp;
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:
using System;
public class Test
{
static Test shared;
string First { get; set; }
string Second
{
set
{
Console.WriteLine("Setting second. shared.First={0}",
shared == null ? "n/a" : shared.First);
}
}
static void Main()
{
shared = new Test { First = "First 1", Second = "Second 1" };
shared = new Test { First = "First 2", Second = "Second 2" };
}
}
The output shows that in the second line of `Main`, when `Second` is being set (after `First`), the value of `shared.First` is still "First 1" - i.e. `shared` hasn'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.
Problem
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?)