With C# 3.0 you can initialize objects specifying the values of their visible properties and/or fields enclosed between brackets. The syntax is as easy as open the brackets and provide a list of name/value pairs separated by commas with all the properties/fields you want to initialize, the value of the field can be an expression or another initializer. Consider that using an object initializer without using the parenthesis of the constructor, is equivalent to invoking the default constructor. Next you a sample of how to initialize the same class with different styles.
Collection initializers allow us adding elements to a collection in a similar way we do in array initializers. The initializer consists of the list of elements we want to add separated by commas and enclosed by brackets. The elements can be single values or other initiliazers, but unlike object initializers they don’t allow expressions to avoid confuse them. Below you can see some samples:
If you build your own collection, there are some requirements that the class must satisfy in order users can take profit of Collection Initializers. The class must implement the IEnumerable interface and must have at least one public "Add" method. Look the next code:
If you change the modifier of the method "Add" to private, the compiler will give the error "Numbers.Add(int) is inaccessible due to its protection level". This gives the hint that the compiler translates the Collection Initializer syntax to as much calls to the matching method Add as elements you add. We can verify it just examining the IL code.
IL_0008: callvirt instance void Demo.Numbers::Add(int32)
IL_000f: callvirt instance void Demo.Numbers::Add(int32)
IL_0016: callvirt instance void Demo.Numbers::Add(int32)
IL_001d: callvirt instance void Demo.Numbers::Add(int32)