Nested properties initialization – syntactic sugar

I think most of developers are familiar with the object syntax initializer, which basically allows you to set up values of properties just like that

In this example the Settings property is assigned with new instance of CustomWebClientSettings class. However for time to time we only want to change particular property of given nested property and leave rest of the object intact. Of course we can write it usual way

but there is a much cooler syntax for that. The code above can be rewritten to

Note that there is no new keyword in the assignment of Settings property, which means that the Settings object is updated with the values of properties in braces. Of course this syntax can be safely used only if the nested property(in this case Settings) is initialized up front in constructor, otherwise you will get NullReferenceException. Source code for this post can be found here

Nested properties initialization – syntactic sugar