Declaring and initializing a string array in VB.NET Declaring and initializing a string array in VB.NET arrays arrays

Declaring and initializing a string array in VB.NET


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 arrayDim i as Integer() = {1, 2, 3, 4} ' Object arrayDim o() = {1, 2, 3} 

Check more info:

Visual Basic 2010 Breaking Changes

Collection and Array Initializers in Visual Basic 2010


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"}


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 IntegerY = 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.