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?)
I'ts syntactic sugar and the compiler generates the same exact IL as it did before object initializers were introduced in .NET 3.5
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.
It is entirely sugar for standard types. For anonymous types, you may find that it uses a constructor behind the scenes, but since the initializer syntax is the only way of assigning them, it is a moot point.
This involves a few more calls than, say, a specific constructor - but I'd be amazed if you ever saw a difference as a result. Just use initializer syntax - it is friendlier ;-o
No there is no performance improvement. Under the hood the compiler will generated assignments to the same properties and fields. It will look just like your expanded version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With