Here's a simple question : Is there any (performance) difference between this :
Person person = new Person()
{
Name = "Philippe",
Mail = "phil@phil.com",
};
and this
Person person = new Person();
person.Name = "Philippe";
person.Mail = "phil@phil.com";
You can imagine bigger object with more properties.
They are almost exactly equivalent except that the first method (using an object initializer) only works in C# 3.0 and newer. Any performance difference is only minor and not worth worrying about.
They produce almost identical IL code. The first gives this:
The second gives this:
As you can see, nearly identical code is generated. See below for the exact C# code I compiled.
Performance measurements show very similar results with a very small performance improvement for using the object initializer syntax:
Code I used for testing the performance:
One additional thing worth noting is this:
If you fail to handle an exception in your constructor, you'll get a TypeInitializationException. While that may not seem so bad, the truth is that it conceals the real cause of the problem, and makes it harder to track down.
If, on the other hand, you use an object initializer, you're invoking each property individually outside of the constructor, and any thrown exceptions will be very clear and very evident: they won't be masked by the TypeInitializationException.
In general, it's a bad idea to throw exceptions in a constructor. If you want to avoid that scenario, go with the initializer.
Performance-wise there is no significant difference, as other replies have shown.
However, creating an object using an initializer with 2 parameters seems to me like you state your intent to anyone who is using it, forming a "contract" saying: "these 2 parameters are the minimum for the functionality of the class" (although the correct way to express that intent would be to use a constructor).
I tend to think of the initializer syntax this way, although it's more or less just syntactic sugar. I use a mix of both syntaxes in my code. But then again, that's my personal style.
As others have said, no, there is no difference. Note that the first example isn't actually using a constructor for those arguments. It's using the "object initializer" language feature introduced in C# 3.0. The constructor being called is the default parameterless constructor just like the second example.
The two examples actually compile down to the same IL code and do exactly the same thing. The first example is just syntactic sugar to accomplish the task <opinion>in an easier and more expressive way</opinion>.
No. The first way is new in .NET 3.5 but the second example is for previous versions of C#.