Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are array initializers only allowed for arrays? [duplicate]

Possible Duplicate:
Collection initialization syntax in Visual Basic 2008?

This does not compile.

Dim Tom As New List(Of String) = {"Tom", "Tom2"}

This does

Dim Tom As String() = {"Tom", "Tom2"}

IMO this features should be allowed for all collection types and not only arrays.

like image 953
Tomasi Avatar asked Mar 01 '10 20:03

Tomasi


People also ask

What does array constants can only be used in Initializers mean?

Because array constants can only be used in initializers. You cant use them when assigning a new value to the variable. You can only use it during the initialization of the variable.

What are array Initializers?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.

What happens when an array is initialized with more Initializers as compared to its size?

An initializer-list is ill-formed if the number of initializer-clauses exceeds the number of members or elements to initialize.

Can an array be initialized twice?

No. The array is not being created twice. It is being created once and then it is being populated.


2 Answers

You cannot do this in the current version of Visual Basic, but the next version in Visual Studio 2010 allows this syntax:

Dim Tom As List(Of String) = new List(Of String) From {"Tom", "Tom2"}

It uses the new From keyword.

C#, on the other hand, has included its collection initializer syntax in Visual Studio 2008. You can read about it Object and Collection Initializers (C# Programming Guide) (MSDN).

like image 133
Nick Avatar answered Nov 15 '22 04:11

Nick


Microsoft agrees with you. It is supported starting in the next release of VB, VB 2010. See this question: Collection initialization syntax in VB 2008?.

MSDN: What's New in Visual Basic 2010?

like image 27
Jim Counts Avatar answered Nov 15 '22 05:11

Jim Counts