tags:

views:

63

answers:

2
Public Function Foo() as String()
Dim bar As String = {"bar1","bar2","bar3"}

Return bar
End Function

My situation is similar to the code sample above where I'm returning a string array from a function.

What I would like to do is just return the string array without having to declare a variable first and then return the variable.

Something like this, although this obviously doesn't work:

Return {"bar1","bar2","bar3"}

Is it possible to do this, I can't seem to find a method that works?

+6  A: 

You could do this:

Public Function Foo() As String()
    Return New String() {"bar1", "bar2", "bar3"}
End Function
Darin Dimitrov
A: 

You do not have to declare a variable (as the example from Darin), but you do have to create an instance of the type you want (a string array).

His example works because he is "newing up" a string array.

Oded
I'm slightly confused by your comment "His example works because he is "newing up" a string array."Darin's suggestion seems to work fine, but is this bad practice perhaps?
Richard
He is returning a _NEW_ string array. Not saying this is bad code, but is explains why your example deosn't work.
Oded
@Richard: He just means that you always have to have a string array instance to return and there's 2 ways of doing it - define a new string array variable, populate that variable and return that (like you're currently doing)....or do it inline like Darin showed, which is just a shortcut as you're returning the new string array directly instead of first assigning it into a variable
AdaTheDev
Exactly that Ada...
Oded