KyleMit
KyleMit

Reputation: 29957

Syntax for Initializing Array of Anonymous Objects

You can initialize an anonymous object like this:

Dim cust = New With {.Name = "Hugo", .Age = 23}

And you can initialize a collection like this:

Dim numbers = {1, 2, 3, 4, 5}
Dim names As New List(Of String) From {"Christa", "Brian", "Tim"}

But can you initialize an array of anonymous object with syntax support

You can do it like this, but custs will just be a plain object:

Dim custs = { New With {.Name = "Hugo", .Age = 23}, New With {.Name = "Boss", .Age = 32} }

You can do it like this, but each item in custs will just be a plain object:

Dim custs As New List(Of Object) From { New With {.Name = "Hugo", .Age = 23}, New With {.Name = "Boss", .Age = 32} }

How can I initialize a list/collection/array such that I can access the full power of the collection and also the properties of the anonymous object type inside

Upvotes: 1

Views: 539

Answers (1)

KyleMit
KyleMit

Reputation: 29957

The problem was with the option for Inferred Typing turned off. This could be illustrated by a simpler example where initialing an object without declaring its type first resulted in a plain, boring object.

= vs. As assignment

To resolve this, you can turn On Inferred Typing with the option statement:

Option Infer On

Now our simple date example should work:

Dim x = New DateTime

Finally, just make sure you compile the the code once because anonymous objects are actually implemented as hidden classes behind the scenes.

enter image description here

Upvotes: 1

Related Questions