Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 415
wayfare Avatar asked Oct 11 '12 14:10

wayfare


People also ask

What is an object initializer?

An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.

What happens when you initialize an object?

Initializing an ObjectThis class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b).

What is object initializer in C#?

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.

What is the difference between initializer and constructor?

Object Initializers were something added to C# 3, in order to simplify construction of objects when you're using an object. Constructors run, given 0 or more parameters, and are used to create and initialize an object before the calling method gets the handle to the created object.


1 Answers

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

like image 83
Jon Senchyna Avatar answered Oct 12 '22 23:10

Jon Senchyna