Is there any benefit of using an Object Initializer?

Are there any benefits in using C# object initializers?

In C++ there are no references and everything is encapsulated inside an object so it makes sense to use them instead of initializing members after object creation.

What is the case for their use in C#?

How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)


Solution 1:

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).

Solution 2:

There is a potential reason to not use object initializers: If there is an exception during initialization, the call stack in Visual Studio debugger will return only the initializer expression and not the specific line where the exception occurred.

If you use libraries or external services that have poorly named exceptions, or alternatively use libraries with native code where you can't see the code that throws the exception (e.g. Xamarin on Android), object initializers can make it harder to debug your code since you don't know which parameter caused the exception to be thrown.

Example: Imagine this is your code, but that you can't read the source of ExternalService since it's external to your application. You will not know that it was the "charlie" parameter that caused the error in ExternalService.

    var instance = new ClassToBeInitialized
    {
        alpha = "alpha", 
        bravo = ExternalService(0),
        charlie = ExternalService(1)
    };

    private static string ExternalService(int parameter)
    {
        if (parameter == 1)
        {
            throw new Exception("The external service crashed");
        }

        return "correctStringResult";
    }

Solution 3:

Benefits are in the usage of anonymous objects, linq queries, sometimes needless overloading of constructors just to pass parameters