Show/Hide Toolbars

XSharp

X# has added two types of initializers to the language: collection Initializers and Object Initializers. The syntax for these is:

 

constructorcall                : datatype { parameterlist? } initializer?
                                     ;
 
initializer                        : objectinitializer
                             | collectioninitializer
                             ;
 
objectinitializer            : { (memberinitializer (, memberinitializer)*)? }
                               ;
 
memberinitializer            : Name=identifierName := Expr=initializervalue
                               ;
 
initializervalue            : objectOrCollectioninitializer
                               | expression
                             ;
 
collectioninitializer          : { expression (, expression)* }
                               ;

Note:

The initializer which is also delimited by curly braces immediately follows the closing curly brace of the constructor call

An example of an object initializer:

 VAR oPerson := Person{}{FirstName := "John", LastName := "Smith"}
  VAR oPerson := Person{"John", "Smith"} {Age := 35 }

An example of a collection initializer

 oList := List<Int>{} {1,2,3,4,5}

And combined:

  Var oPeople := List<Person> {} {;
                                      Person{}{FirstName := "John", LastName := "Smith"}, ;
                                      Person{}{FirstName := "Jane", LastName := "Doe"} ;
                                }

The LINQ example topic shows different initializers in action.