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[]?

4
  • Cast it? var newObjects = objects as string[]; If it is actually that type then it you are done. If not newObjects will be null. Commented Jun 8, 2016 at 22:34
  • Just loop through it? var objects = apiResult; foreach (var object in objects) {...} Commented Jun 8, 2016 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[] Commented Jun 8, 2016 at 22:48
  • Have you seen this question? Does it help at all? stackoverflow.com/questions/15586123/… Commented Jun 8, 2016 at 22:54

1 Answer 1

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(); 
Sign up to request clarification or add additional context in comments.

3 Comments

I wish I was allowed to use a comment to say "very neat"
@EvanL Read the quote.
I stand corrected, ran a few samples of this myself. Forgot how magical the Cast<T>() method could be!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.