Reputation: 31
I am newbie in VB.NET. When I read the document on MSDN (https://msdn.microsoft.com/en-us/library/vstudio/bb534304%28v=vs.100%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1) I see the following code (excerpt):
Dim pets As New List(Of Pet)(New Pet() _
{New Pet With {.Name = "Barley", .Age = 8}, _
New Pet With {.Name = "Boots", .Age = 4}, _
New Pet With {.Name = "Whiskers", .Age = 1}, _
New Pet With {.Name = "Daisy", .Age = 4}})
I don't see the definition of class Pet before. Can anyone explain it to me?
Upvotes: 1
Views: 97
Reputation: 415705
This is confusing, because VB.Net re-uses some tokens in this case to mean different things. I'll spread the code over several lines and explain what happens at each point.
Dim pets As New List(Of Pet)
That creates a list object that will hold Pet objects.
(
We are calling the constructor for the List(Of Pet) type. There are several overloads for the List(Of T) constructor, but the code here uses this one.
New Pet()
This is where it gets tricky. This code is not creating a new Pet
object. In this context, the ()
tokens indicate that this will be an array.
_
That just moves the code to the next line
{
This now indicates that we are in a Collection Initializer, which is used to immediately populate a new Array/List/etc with items.
New Pet
This time we are creating a new Pet object.
With {
This indicates that we're using an Object Initializer. It's worth mentioning here that the only cue the compiler has for the difference between the New Pet() as an array and New Pet() as an object in this case is the use of the initializers, and the only difference between the two kinds of initializer is the With
keyword. It can make code like this in VB confusing, if you're not used to it.
.Name = "Barley", .Age = 8}
Assign some values to properties for the new object, and finish the object initializer.
, _
Move to the next item in the collection initializer, and continue on another line.
New Pet With {.Name = "Boots", .Age = 4}, _
New Pet With {.Name = "Whiskers", .Age = 1}, _
New Pet With {.Name = "Daisy", .Age = 4}
Just like with the previous code, this creates three more new Pet objects and sets values for some of their properties. Note that there is no comma (,) after the last entry.
})
Now we close the collection initializer, and complete the call to the List constructor.
Upvotes: 1