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>
orobject[]
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 anint
. 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 theobject
overload ofString.Join
which results in an output ofSystem.Int32[]
-- there is unfortunately noIEnumerable
overload, onlyIEnumerable<T>