Search code examples
c#ienumerable

How do I String.Join a boxed array?


Given an object that may contain an array (e.g. int[]), how do I call the correct IEnumerable<T> String.Join overload?

var a = new []{1,2,3};
object o = a;

String.Join(",", a); // "1,2,3"
String.Join(",", o); // "System.Int32[]"

I would like the String.Join on o to be the array's contents, not the type name.


Full context and attempts below

I have an object that can contain anything, including various IEnumerable<T> and arrays e.g. Int32[]. I have a method that converts it to an appropriate string depending on the type:

private string ResultToString(object result)
{
    return result switch
    {
        string res => res,
        IEnumerable<object> enumerable => String.Join(", ", enumerable),
        null => "*null*",
        _ => result.ToString()
    };
}

Currently, if result is an int[], it falls through to the default case.

  • I can't cast the object to IEnumerable<object> or object[] because it's a value array
  • I could cast the object to IEnumerable<int> but I don't know ahead of time that it is an int. I would like to avoid having to list a case for every value type (and wouldn't include structs?)
  • I can cast the object to IEnumerable but that just calls the object overload of String.Join which results in an output of System.Int32[] -- there is unfortunately no IEnumerable overload, only IEnumerable<T>

Solution

  • You can cast to IEnumerable and then use Cast<T> which always succeeds with Object:

    private string ResultToString(object result)
    {
        IEnumerable enumerable = result as IEnumerable;
        if(enumerable == null) return result?.ToString();
        return string.Join(", ", enumerable.Cast<object>());
    }
    

    This calls this String.Join overload. Remarks:

    Join<T>(String, IEnumerable<T>) is a convenience method that lets you concatenate each member of an IEnumerable collection without first converting them to strings. The string representation of each object in the IEnumerable collection is derived by calling that object's ToString method.