Isuru
Isuru

Reputation: 31283

Returning a string array as a single string from a method

I have a string array variable.

private string[] _documents;

Values to it are assigned like this.

string[] _documents = { "doc1", "doc2", "doc3" };

And there's a method which adds a string to that array and returns it.

public string GetMail()
{
    return originalMessage + " " + _documents[0];
}

Defining _documents[0] returns only the first element of the array.

How can I return all the elements in the array? (Kinda like what implode function does in PHP)

Upvotes: 3

Views: 9765

Answers (3)

Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

public string GetMail()
{
    return originalMessage + string.Join(" ", _documents);
}

Upvotes: 1

evanmcdonnal
evanmcdonnal

Reputation: 48076

Loop over them and append each to the original string.

 public string GetMail(string[] docs, string originalMessage)
 {
        for (int i = 0; i < docs.Length; i++)
              originalMessage = originalMessage + " " + docs[i];

         return originalMessage;
  }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

I am not familiar with PHP, but you can concatenate all elements of a string array with string.Join:

return string.Join(" ", docs);

The first parameter is the separator; you can pass an empty string if you do not need separators.

Upvotes: 7

Related Questions