Skip to content

Collection initializers

Andrey Kurosh edited this page Jun 18, 2017 · 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

let 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

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

Due to the limitations of the .NET framework, a tuple cannot contain more than 7 items. For more values, please use a record. Nested tuples also work, but this approach is inferior because it results in clumsy code.

Complex expressions

If the collection must be initialized with more complex expressions, there is a multiline indented syntax:

let values = new [
    fmt "{0} and {1}" 1 2
    fmt "and also {0}" 42
]

Each expression is on its own line without any additional separator. Notice the placement of opening and closing brackets.

Read more

Clone this wiki locally