Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring and initializing a string array in VB.NET

I was trying to return an array of strings from a function and got surprised by an error.

I would have expected this to work, but it produces an error:

Public Function TestError() As String()     Return {"foo", "bar"} End Function 

This works:

Public Function TestOK() As String()     Dim ar As String() = {"foo", "bar"}     Return ar End Function 

As does:

Public Function TestOK() As String()     Return New String() {"foo", "bar"} End Function 

I guess I'm unclear on the meaning of the {}'s - is there a way to implicitly return a string array without explicitly creating and initializing it?

like image 331
chris Avatar asked Mar 10 '11 16:03

chris


1 Answers

Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.

In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:

' Integer array Dim i as Integer() = {1, 2, 3, 4}   ' Object array Dim o() = {1, 2, 3}  

Check more info:

Visual Basic 2010 Breaking Changes

Collection and Array Initializers in Visual Basic 2010

like image 172
pirho Avatar answered Sep 30 '22 20:09

pirho