11
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?

2 Answers 2

15

You could do this:

Public Function Foo() As String()
    Return New String() {"bar1", "bar2", "bar3"}
End Function
Sign up to request clarification or add additional context in comments.

Comments

3

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.

3 Comments

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?
He is returning a NEW string array. Not saying this is bad code, but is explains why your example deosn't work.
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.