I have an object whose value may be one of several array types like int[] or string[], and I want to convert it to a string[]. My first attempt failed:
void Do(object value)
{
if (value.GetType().IsArray)
{
object[] array = (object[])value;
string[] strings = Array.ConvertAll(array, item => item.ToString());
// ...
}
}
with the runtime error Unable to cast object of type 'System.Int32[]' to type 'System.Object[]', which makes sense in retrospect since my int[] doesn’t contain boxed integers.
After poking around I arrived at this working version:
void Do(object value)
{
if (value.GetType().IsArray)
{
object[] array = ((Array)value).Cast<object>().ToArray();
string[] strings = Array.ConvertAll(array, item => item.ToString());
// ...
}
}
I guess this is OK, but it seems pretty convoluted. Anyone have a simpler way?
You don’t need to convert it to an array and then use LINQ. You can do it in a more streaming fashion, only converting to an array at the end:
(Note that this will preserve nulls, rather than throwing an exception. It’s also fine for any
IEnumerable, not just arrays.)