Convert string to an array of strings on the fly

I have a method that returns an array of strings. In that method I am processing only one string, and I want to return it as an array of strings (an array of strings with only one element, which is my string → array[0] == myString).

I want that because I want to avoid some ugly code for creating an array of strings with one element, like that:

private static string[] FooterContent()
{
      string[] array = new string[1];
      array[0] = GetMyData();
      return array;        
}

I want something like that:

private static string[] FooterContent()
{
      string myData = GetMyData();
      return myData.ToArray();        
}

And that myData.ToArray() should create an array with only one element (array[0] = myString) and then to return it.

Or, something like that (if possible):

private static string[] FooterContent()
{
     return GetMyData().ToArray();        
}

The point is that I can't simply modify the return type from string[] to string because I am using the value returned from FooterContent (array of strings) and from other similar methods, like BodyContent or HeadContent, into another general method, WriteContent() that accepts an array of strings.

Is there an elegant way of doing this?

Thank you respectfully.

Jon Skeet
people
quotationmark

As w0lf suggested in comments, the simplest way of creating an array would just be:

return new[] { GetMyData() };

While you could create an extension method, I personally wouldn't - and if you do, you absolutely should not call it ToArray, as that already has a meaning for string due to Enumerable.ToArray and the fact that string implements IEnumerable<char>.

If you really, really want to create this extension method, I'd do it as:

public static T[] ToSingleElementArray(this T value)
{
    return new[] { value };
}

Then you can use:

return GetMyData().ToSingleElementArray();

But as I said, I wouldn't even create the extension method...

people

See more on this question at Stackoverflow