66

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)

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
wayfare
  • 1,802
  • 5
  • 20
  • 37
  • 3
    It is syntactic sugar to save some keystrokes and get code onto a single executable statement (for stuff like inline linq calls). The style is also borrowed for anonymous type creation: `new { FirstName = "Adam", Age = 27 };` – Adam Houldsworth Oct 11 '12 at 14:51
  • Please, do not include information about a language used in a question title unless it wouldn't make sense without it. Tags serve this purpose. – Ondrej Janacek Feb 28 '14 at 07:32
  • u edited 18 months old question – Sandeep Singh Rawat Feb 28 '14 at 07:57
  • 10
    @SandeepSinghRawat there's nothing wrong with editing old posts, as long as there is a good reason for doing it. –  Apr 17 '14 at 22:31

5 Answers5

116

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

Jon Senchyna
  • 7,867
  • 2
  • 26
  • 46
  • 4
    Won't atomicity be preserved if `FirstName`, `LastName` and `ID` were initialized inside `StudentName`'s constructor? – Songo Mar 21 '14 at 12:21
  • 3
    Yes, it would. The above statement about atomicity is for when you need to initialize properties of your object outside of the constructor. Some examples of this are cases where you cannot change the constructor code, or where your object has a large number of optional properties that you want to set without creating dozens of overloaded constructors. – Jon Senchyna Mar 21 '14 at 21:02
48

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";
    }
James Wierzba
  • 16,176
  • 14
  • 79
  • 120
Geir Smestad
  • 1,344
  • 2
  • 15
  • 25
  • 10
    I ended up in this post exactly to check if anyone claims the same. This has been being debated in my team in the past weeks. I as a developer do like the syntax sugar it provides (the other benefits pointed above are not relevant to my context) - but I can accept this as a reason strong enough not to use it (in cases such as mine where you do not benefit from anything else in using it). – Veverke Dec 03 '15 at 11:12
  • 1
    We have also found many cases where the object initializer syntax makes debugging complex models virtually impossible due to the number of properties and external vendor models involved. –  Mar 15 '18 at 17:06
16

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

AD.Net
  • 13,352
  • 2
  • 28
  • 47
  • +1 It also allows implicit typing for such parameters, rather than having to write new MyType() {.... } everywhere. – cirrus Oct 11 '12 at 15:02
  • 3
    You can also get around the needless overloading of constructors by using named and optional parameters in your constructor: http://msdn.microsoft.com/en-us/library/dd264739.aspx – Jon Senchyna Oct 11 '12 at 15:52
1

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 };
Rudey
  • 4,717
  • 4
  • 42
  • 84
Debendra Dash
  • 5,334
  • 46
  • 38
0

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.

Kirby
  • 3,649
  • 3
  • 26
  • 28
  • 2
    Your answer is a bit confusing. It looks like you're suggesting using private setters and object intializer syntax to create functionality similar to a readonly property. If you make your setters private, they cannot be used with object initializer syntax unless you're using it in a location that already has access to those private setters. – Jon Senchyna Oct 11 '12 at 15:50
  • I agree. I should have worded it better. To answer the OP, I'm really only saying that I think that it promotes readability. The remainder of what I wrote is a bit off-topic. I've edited the text to try to reflect this. – Kirby Oct 11 '12 at 16:45