3

This morning, I had a discussion with a co-worker regarding the following two example of initializing the code.

Example 1:

var employee = new Employee();
employee.FirstName = GetFirstName();  // this may get values from db

Example 2:

var employee = new Employee() 
{
    FirstName = GetFirstName()
}

My co-worker's argument was that example 2 is more efficient and if that object has any errors during initialization, it is automatically removed from heap. I am thinking that the compiled version of the code would look similar to example 1.

My question is that is my co-worker correct in his argument? When should you use property assignment instead of object initialization? Are there any best practices around this? MS doesn't have anything ...

Skadoosh
  • 2,575
  • 8
  • 40
  • 53
  • 2
    They're literally the same thing. Check the IL. –  Mar 27 '19 at 14:08
  • Generated code is the same, while example 1 has better (more exact) line numbers if an exception occurs. – Caramiriel Mar 27 '19 at 14:08
  • This is a compiler feature, not a run-time feature – Emond Mar 27 '19 at 14:09
  • @Caramiriel I forgot to mention in my orig post but that was my counter argument too. – Skadoosh Mar 27 '19 at 14:09
  • Some general remarks. Calling database should be responsibility of other class, your constructor should receive just a value and initialize it. Although it is the same you should create and initialize the object fully within constructor, so from that point 2. example is better... – Johnny Mar 27 '19 at 14:11
  • 1
    Just go to the C# spec. 12.7.11.3 Object initializers: "A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (§12.18.2) to the field or property." – Raymond Chen Mar 27 '19 at 14:12

0 Answers0