1

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.

12
  • 1
    What is GetMyData and what does that return? Commented Aug 28, 2015 at 7:16
  • GetMyData returns a string Commented Aug 28, 2015 at 7:17
  • Why not just have that return an array? or better yet, an object? Commented Aug 28, 2015 at 7:17
  • 7
    why not just do new [] { yourstringhere } then? Commented Aug 28, 2015 at 7:18
  • 1
    This sounds like an XY Problem... What is it you are trying to achieve? Without knowledge of what GetMyData is doing its hard to give an answer.. Commented Aug 28, 2015 at 7:20

4 Answers 4

8

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...

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

Comments

4

You can:

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

or write extension method which isn't the best approach here (but possible):

public static class StringExtensions
{
    public static string[] ToSingleElementArray(this string inputString)
    {
        return new[] { inputString };
    }
}

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

2 Comments

Calling it ToArray is a bad idea IMO, due to the collision with Enumerable.ToArray.
Correct! ToArray isn't proper name here - let's change it to something you suggested
3

Try this,

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

Comments

1

Alternatively, you can wrap your GetData return value in a struct and use implicit operators to perform conversions:

public struct DataResult
{
    private string _raw;
    private string[] _rawArray;

    public DataResult(string raw)
    {
        _raw = raw;
        _rawArray = new [] { raw };
    }

    private string Raw { get { return _raw; } }
    private string[] RawArray { get { return _rawArray; } }

    public static implicit operator string(DataResult result)
    {
        return result.Raw;  
    }

    public static implicit operator DataResult(string rawResult)
    {
        return new DataResult(rawResult);
    }

     public static implicit operator string[](DataResult result)
     {
         return result.RawArray;
     }

    public static implicit operator DataResult(string[] rawResultArray)
    {
        if(rawResultArray == null || rawResultArray.Length != 1)
            throw new ArgumentException("Raw result must be a single item array", "rawResultArray");

        return new DataResult(rawResultArray[0]);
    }
}

Implicit operators let you do implicit conversions from apples to pears (and viceversa):

DataResult result = new DataResult("hello world");
string[] resultArray = result;
string rawResult = result;

DataResult result2 = new string[] { "hello world" };
DataResult result3 = "hello world";

What does it mean? If your GetData method returns DataResult any other code can set its value to a string, string[] or DataResult, and perform the opposite conversions implicitly.

I believe that in your case, this should be one of best approaches.

4 Comments

Seems like a world of pain to me in terms of readability - and the fact that the struct is mutable is even nastier, IMO.
@JonSkeet well, I can turn it to immutable
@JonSkeet BTW there's always a discussion about readibility about implicit operators... Sometimes is a good solution. For example, StackExchange.Redis does it extensively and I wouldn't argue that it reduces readability in your code. And in my own code I use implicit operators. Right, my #1 choice are extension methods or other approaches, but tools are still there to be used in edge cases
Oh I agree that sometimes they're appropriate - I just don't think this is one of those times. (Nor would I bother with the struct at all, but that's a different matter.)

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.