1

I have a line in my code:

var objects = ExternalApiGetObjects(....);

At develop time I only know that ExternalApiGetObjects returns an Object instance. In fact, I'm sure that objects variable is an array of some type. I want to pass objects variable to String.Join method, but in runtime I got an exception similar to this: "Object of type 'System.Int32[]' cannot be converted to type 'System.String[]'."

In most cases, an objects will not be a string array. It could be an int array, or even an array of some user's type. I just know that objects is an array and I want to invoke ToString() on each item of that array to create a new one with type of string[].

How can I convert my objects to string[]?

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
  • Cast it? `var newObjects = objects as string[];` If it is actually that type then it you are done. If not `newObjects` will be null. – Matt Rowland Jun 08 '16 at 22:34
  • Just loop through it? `var objects = apiResult; foreach (var object in objects) {...}` – Austin T French Jun 08 '16 at 22:44
  • In most cases, an `objects` will not be a string array. It could be an int array, or even an array of some user's type. I just know that `objects` is an array and I want to invoke `ToString()` on each item of that array to create a new one with type of `string[]` – Aleks Andreev Jun 08 '16 at 22:48
  • Have you seen this question? Does it help at all? http://stackoverflow.com/questions/15586123/loop-through-object-and-get-properties – Bassie Jun 08 '16 at 22:54

1 Answers1

5

OP: It could be an int array, or even an array of some user's type. I just know that objects is an array and I want to invoke ToString() on each item of that array to create a new one with type of string[]

You can cast it to IEnumerable, then using Cast<T> convert elements to object and then select elements. For example:

object o = new int[] { 1, 2, 3 };
var array = (o as IEnumerable).Cast<object>().Select(x => x.ToString()).ToArray(); 
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398