Is there any benefit of using an Object Initializer?
Asked Answered
E

5

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)

Expiable answered 11/10, 2012 at 14:49 Comment(4)
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 };Suzettesuzi
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.Samos
u edited 18 months old questionWebster
@SandeepSinghRawat there's nothing wrong with editing old posts, as long as there is a good reason for doing it.Lytle
M
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).

Middlebrow answered 11/10, 2012 at 14:55 Comment(2)
Won't atomicity be preserved if FirstName, LastName and ID were initialized inside StudentName's constructor?Ferullo
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.Middlebrow
E
49

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";
    }
Emunctory answered 9/6, 2015 at 11:26 Comment(2)
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).Alfrediaalfredo
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.Joint
B
16

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

Bahaism answered 11/10, 2012 at 14:51 Comment(2)
+1 It also allows implicit typing for such parameters, rather than having to write new MyType() {.... } everywhere.Loading
You can also get around the needless overloading of constructors by using named and optional parameters in your constructor: msdn.microsoft.com/en-us/library/dd264739.aspxMiddlebrow
S
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.

Scabrous answered 11/10, 2012 at 14:56 Comment(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.Middlebrow
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.Scabrous
H
0

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 };
Hebbe answered 16/5, 2017 at 14:55 Comment(1)
Generally speaking, converting multiple lines into one line, while retaining most of the same structure, is not a simplification. Eliminating "emp." from each assignment is a simplification. But there is nothing stopping you in C# from joining a million statements into one line.Consider

© 2022 - 2024 — McMap. All rights reserved.