Skip to content

Collection initializers

Andrew edited this page Oct 25, 2013 · 7 revisions

LENS provides a simple way to initialize some common collections with data. The new keyword is used with a specific pair of brackets.

The collection type is inferred from arguments. If the collection contains values of different types, the best common type is used.

Collections can contain null values, but there must be at least one non-null expression to infer the type from. Casting the null to a particular type also works.

Arrays

let arr = new [1; 2; 3]
arr.Length                  // 3

Lists

let list = new [[1; 2; 3]]
list.Add 4
list.Count                  // 4

Dictionaries

var dict = new { "hello" => 5; "world" => 42 }

Any type can be used as a key for the dictionary, provided it implements the GetHashCode and Equals methods - this is required by the Dictionary<TKey, TValue> type. All the keys must have exactly the same type: the best common type is inferred for values only.

Tuples

var tuple = new (1; "hello"; true)

The tuple can contain a maximum of 7 items. For more values, please use a record.

Clone this wiki locally