Object and Array Initializers in VB 9

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s