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)
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.
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).
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With