WARNING: This is a speculative post. Caveat emptor.
Well, I appear to be on a rhythm of about once a month posts, which seems OK for the moment. Moving on to another “future” topic, one of the most annoying things that we cut (at least, from my perspective) from VB 2008 was collection initializers. Collection initializers were a little different than the corresponding C# feature, because our plan was to introduce stand-alone initializers that didn’t have any intrinsic type. Instead the initializers “snap to” a particular type when they’re converted to it, just like lambdas and AddressOf expressions. For example:
' This works since VB 7.0!
Dim a() As Integer = {1, 2, 3, 4}
' This now creates a list.
Dim b() As List(Of Integer) = {1, 2, 3, 4}
' This assigns a new list to b.
b = {5, 6, 7, 8}
' If M takes Integer(), that's what it'll get. If it takes List(Of Integer), that's what it'll get.
M({1, 2, 3, 4, 5})
This is kind of nice, in that you can initialize collection types and arrays without having to state a type at all. We do the same trick C# does about looking for an Add method on a object that implements IEnumerable, so you can also use this syntax to initialize dictionaries:
Dim d As Dictionary(Of Integer, String) = {{1, "One"}, {2, "Two"}, {3, "Three"}}
All this is pretty straightforward, but there is some discussion about what type you should get if there is an absence of a target type. For example, assuming that local type inference is on, what should the following be typed as?
Dim x = {1, 2, 3, 4}
Our initial thought was that we should just infer the dominant type of the initializer and then create an array of that type. So the above example would type x as Integer(). And then the following:
Dim y = {{1, 2}, {3, 4}, {5, 6}}
Would infer a type of Integer(,), a two-dimensional array of Integer. With more nesting, you’d get more dimensional arrays. However, as we talked about it more, it seemed like maybe it might be more useful to infer List(Of T) for the 1-dimensional initalizer, Dictionary(Of K, V) for the 2-dimensional initializer, and nothing for more dimensions. So the type of x would instead be List(Of Integer) and the type of y would be Dictionary(Of Integer, Integer).
Both seem reasonable, so I’m curious what people would think. Remember, we will only fill in a type if we’re in a context (like type inference) where there’s no target type to use. We’ll always use a target type if there is one.