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?
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
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 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.
精彩评论