Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer syntax

I like the C# 3 initializer syntax and use it a lot, but today while looking in Reflector, the following came up:

var binding = new WSHttpBinding {   ReaderQuotas = { MaxArrayLength = 100000 },   MaxReceivedMessageSize = 10485760 }; 

At first I thought it was a mistake, but it does compile! Guess I am still learning new stuff all the time. :)

From what I can tell, it sets the MaxArrayLength property of the ReaderQuotas property of the WSHttpBinding.

Does this syntax create a new ReaderQuotas object and then set the property, or does it assume the property to be initialized already? Is this the general way one would use to initialize 'child' properties?

I do find the syntax a bit confusing...

like image 240
leppie Avatar asked Jan 07 '10 12:01

leppie


People also ask

What is initialization syntax?

C# - Object Initializer Syntax NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor. Example: Object Initializer Syntax.

What is object initializer syntax?

The object initializers syntax allows you to create an instance, and after that it assigns the newly created object, with its assigned properties, to the variable in the assignment. Starting with C# 6, object initializers can set indexers, in addition to assigning fields and properties.

What is an initializer C++?

The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters.

What is type initializer in C#?

Type Initializers are a new language construct that allow for C# (and VB using similar syntax) to shortcut creating of custom constructors or writing additional code to initialize properties.


1 Answers

No, that doesn't create new objects unless you use = new SomeType {...}:

var binding = new WSHttpBinding {     ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = 100000 },     MaxReceivedMessageSize = 10485760 }; 

Your example shows the initializer syntax for setting properties of existing sub-objects. There is also a similar syntax for calling "Add" methods on collections.

Your code is broadly comparable to:

var binding = new WSHttpBinding(); binding.ReaderQuotas.MaxArrayLength = 100000; binding.MaxReceivedMessageSize = 10485760; 
like image 128
Marc Gravell Avatar answered Sep 21 '22 13:09

Marc Gravell