2

what's the best method to return a variable length string array

4 Answers 4

14

I'd prefer to use a generic collection such as: List<string> (or IList<string>), or IEnumerable<string> depending on how you plan to use it. Generic collections are typically easier to work with than arrays, having a much more robust interface.

Sign up to request clarification or add additional context in comments.

7 Comments

if using generic collection, can I convert it to an array?
Yes, by using the toArray() member method.
Yes, they have a .ToArray() method.
@user Yes, you can. But don't. In .Net, you should really avoid arrays entirely in favor of collections. Not that you'll never use arrays, but prefer collections as much as possible.
I usually go with the IEnumerable<string> implementation
|
6

There is nowhere near enough detail in your question to understand exactly what you are after.

This works though:

string[] GetStringArray(int length) {
    return new string[length];
}

(C# isn't like C, if that is your concern.)

Comments

2
public String[] someFunction(){
    String[] variableLengthStringArray = new String[5]();

    // some logic

    return variableLengthStringArray;
}

Comments

1

In the old .NET 1, there was the StringCollection class. it is still supported, and required in a few places, but I would prefer the generic List collection. Or there's the old C-style string[] as per the first answer.

You don't give any specifics, so everything else being equal, I would go for the generic list.

Comments

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.