Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Collection initializers

2009-06-25

There are only a few new changes and additions made to the language Visual Basic in version 10. Changes in version 7, 8 and 9 were huge, and from version 9, I really like what it has become, and all that is needed in version 10 is some polishing. I will spend a few posts on some of the features.

In version 9, we got object initializers and in Visual Basic 10 the initializers will work for arrays and collections. Microsoft call them Collection Initializers. This is a good example of polishing, because the object initializers did not help that much, especially not if you have implemented the constructors that you desire.

A Collection Initializer is a different story. Here, we actually accomplish something useful.

Now, we can create a collection and initialize it with some elements that also are initialized, all in one single line!

The syntax is:

Dim Variable = New CollectionClass = {{element initialization}, {element initialization}, …}

If you want to initialize a collection of objects, and each object is initialized with two integer values (this could be a polygon with points), the could would look like this (if I use the generic collection):

Dim C = New List(Of MyPoint) From {{10, 20}, {15, 25}, {30, 40}}

This would require 4 lines in Visual Basic 9. One to create the collection, and one for each element. If you like, you can break the line at a comma in Visual Basic 10. Good for formatting.

Categories: VB.NET

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips