Skip to content

Collection initializers

impworks edited this page Oct 11, 2014 · 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.

Clone this wiki locally