object to string array

You can use the fact that every array implements IEnumerable:

string[] arr = ((IEnumerable)obj).Cast<object>()
                                 .Select(x => x.ToString())
                                 .ToArray();

This will box primitives appropriately, before converting them to strings.

The reason the cast fails is that although arrays of reference types are covariant, arrays of value types are not:

object[] x = new string[10]; // Fine
object[] y = new int[10]; // Fails

Casting to just IEnumerable will work though. Heck, you could cast to Array if you wanted.

Leave a Comment