Initializer syntax

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 … Read more

Nested object initializer syntax

This syntax is called Object Initialization. C# specification clearly gives a lot of examples on this subject: 7.6.10.2 Object initializers An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. Each member initializer must name an accessible field or property of the object being initialized, … Read more

How to debug object initializer code?

Object initializers should be kept for simple object initialization. If you are in the point where your object constructor has code that may fail (e.g. throwing an exception), don’t use it. Better rely on an object construction pattern, which depending on your needs may be a factory method, an abstract factory,etc… This also ensures that … Read more

Initial capacity of collection types, e.g. Dictionary, List

If the default values are not documented, the reason is likely that the optimal initial capacity is an implementation detail and subject to change between framework versions. That is, you shouldn’t write code that assumes a certain default value. The constructor overloads with a capacity are for cases in which you know better than the … Read more

Constructor vs Object Initializer Precedence in C#

From the documentation: The compiler processes object initializers by first accessing the default instance constructor and then processing the member initializations. This means that in the simplest case (named object initialization) it is basically shorthand (or syntactic sugar) for calling the default constructor and then calling the property setter(s). In the case of anonymous types … Read more

What should my Objective-C singleton look like? [closed]

Another option is to use the +(void)initialize method. From the documentation: The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is … Read more