Is there any benefit of using an Object Initializer?

C#.NetMemory Management

C# Problem Overview


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)

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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

Solution 4 - C#

There are 3 main benefits of object Initialization

  • Avoid lot of keystrokes,The efficiency of software programs is sometimes measured by the number of keystrokes it requires to write a specific function.
  • Easy to readable and maintainable.
  • Time saving approach.

Let see here how it can avoid lot of keystrokes:

Before C# 3.0 we were doing initialization like this:

Employee emp = new Employee();
emp.Name = "Kumar";
emp.Department = "IT";
emp.Id = 101;
emp.Salary = 80000;

Now after C# 3.0 we will initialize in one line as follows:

Employee emp = new Employee { Name = "Kumar", Department = "IT", Id = 101, Salary = 80000 };

Solution 5 - C#

I think that it promotes readability.

As a side note, in the example given in the link shown, I sometimes prefer to have a private setter for the properties (FirstName and LastName), but this depends on your design.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwayfareView Question on Stackoverflow
Solution 1 - C#Jon SenchynaView Answer on Stackoverflow
Solution 2 - C#Geir SmestadView Answer on Stackoverflow
Solution 3 - C#AD.NetView Answer on Stackoverflow
Solution 4 - C#Debendra DashView Answer on Stackoverflow
Solution 5 - C#KirbyView Answer on Stackoverflow