Object and Array Initializers in VB 9

Date July 28, 2007

You can create a new object and initialize some of its properties in one shot. Most examples online are in C#, so here is an example in VB:

Dim mycar As New Car() With {.HasWheels = 4, .NumberOfAirbags = 2, .Passengers = 4}

As for array initialization, it looks like this:


Dim cars() = {New Car With {.Passengers = 4}, New Car With {.Passengers = 2}}

According to MSDN it says I can do it this way:


Dim cars = {New Car With {.Passengers = 4}, New Car With {.Passengers = 2}}

But that didn’t work for me and it gave the error: “Array initializers are valid only for arrays, but the type of ‘cars’ is ‘Object’” So I guess type inference doesn’t work with array initialization. This also doesn’t work with collections or array lists - ONLY arrays.

kick it on DotNetKicks.com

Trackbacks

close Reblog this comment
blog comments powered by Disqus