Is there any benefit of using an Object Initializer?

One often missed benefit is atomicity. This is useful if you’re using double-checked locking on an object. The object initializer returns the new object after it has initialized all of the members you told it to. From the example on the MSDN article:

StudentName student = new StudentName
{
    FirstName = "Craig",
    LastName = "Playstead",
    ID = 116
};

Would be translated to something like the following:

StudentName _tempStudent = new StudentName();
_tempStudent.FirstName = "Craig";
_tempStudent.LastName = "Playstead";
_tempStudent.ID = 116;

StudentName student = _tempStudent;

This ensures that student is never partially initialized. It will either be null or fully initialized, which is useful in multi-threaded scenarios.

For more info on this, you can check out this article.

Another benefit is that it allows you to create anonymous objects (for instance, to create a projection or to join on multiple keys in LINQ).

Leave a Comment