Power7: Dictionary and list literals

[This post is part of a series, “wish-list for future versions of VB“]


IDEA: Dictionary literals. You should be able to write a dictionary initializer with an easier syntax. Moreover, if the user didn’t specify the type of the dictionary, then the compiler should infer the best type using its “Dominant Type” algorithm. For example,

        Dim x As Dictionary(Of Integer, String) = {1:“hello”, 2:“there”, 3:“world”}

        Dim y = {1:“hello”, 2:“there”, 3:“world”}


IDEA: Literals which take their type from their context (to allow list literals). When you write a collection-literal of some sort, it should take its type from its context. For example,

    Sub f(ByVal x As List(Of Double))


    f({1.2, 3})

    Dim a As List(Of String) = {1, “hello”}

    Dim b As ImmutableList(Of Integer) = {1, 2, 3}


As background to the second idea, note that array literals today will ALWAYS produce arrays. The thing is that sometimes you want lists or other user-defined data-structures. One way to do this with Dev10 is to pass the array as a constructor argument to your data-structure, but this won’t work in the “a” case (because of type mismatch) and won’t work in the “f” case (because you’re not writing a constructor). Another way to do this in Dev10 is to write a user-defined-conversion from T() to List(Of T). This works in all cases above.


Provisional evaluation from VB team: A decent idea, but it needs a more concrete design and set of scenarios before we go anywhere with it.

In the case “a” above where we want a List, it would make sense to call Add(1) : Add(“hello”) like we already do with collection-initializers. But for the second one,

Comments (3)

  1. Dzonny says:

    I like both ideas – dictionary initializers and list initializers.

    One more idea, scenario I often miss, is less verbose possibility to initialize array or list of any non-abstract type. Imagine this:

    Public Class SomeClass

       Public Sub New (ByVal a As Integer, ByVal b As String, ByVal c as Char)

       End Sub

    End Class

    Dim arr As SomeClass() = {New SomeClass(7, "7", "7"c), New SomeClass(0, "0", "0"c), New SomeClass(66, "xx", "*"c)}

    Would it be nice to type something shorter instead, like:

    Dim arr As SomeClass() = {{7, "7", "7"c}, {0, "0", "0"c}, {66, "xx", "*"c}}


  2. Kyralessa says:

    I like these ideas.  They save typing but are still easy to understand at first glance.

  3. weitzhandler says:

    First idea: I like it but I think it's too late.

    Second idea: I do think it's compelling, but why not just have an IEnumarable(Of T) constructor-parameter so it ports it to this one