chris
chris

Reputation: 37460

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?

Upvotes: 52

Views: 153218

Answers (3)

Frosty840
Frosty840

Reputation: 8335

I believe you need to specify "Option Infer On" for this to work.

Option Infer allows the compiler to make a guess at what is being represented by your code, thus it will guess that {"stuff"} is an array of strings. With "Option Infer Off", {"stuff"} won't have any type assigned to it, ever, and so it will always fail, without a type specifier.

Option Infer is, I think On by default in new projects, but Off by default when you migrate from earlier frameworks up to 3.5.

Opinion incoming:

Also, you mention that you've got "Option Explicit Off". Please don't do this.

Setting "Option Explicit Off" means that you don't ever have to declare variables. This means that the following code will silently and invisibly create the variable "Y":

Dim X as Integer
Y = 3

This is horrible, mad, and wrong. It creates variables when you make typos. I keep hoping that they'll remove it from the language.

Upvotes: 8

pirho
pirho

Reputation: 3042

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

Upvotes: 56

msarchet
msarchet

Reputation: 15242

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

Works fine for me and should work for you, but you may need allow using implicit declarations in your project. I believe this is turning off Options strict in the Compile section of the program settings.

Since you are using VS 2008 (VB.NET 9.0) you have to declare create the new instance

New String() {"foo", "Bar"}

Upvotes: 15

Related Questions